I\'m looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions.
There is another way to do this in Java 8. I am doing 2 things to accomplish what I needed:
java.util.Optional
java.util.Objects.requireNonNull
Example:
Edit: Disregard this 1st example, I'm just leaving here as context of the comments conversation. Skip to recommended option after this (2nd code block).
import static java.util.Objects.requireNonNull;
public class Role {
private final UUID guid;
private final String domain;
private final String name;
private final Optional description;
public Role(UUID guid, String domain, String name, Optional description) {
this.guid = requireNonNull(guid);
this.domain = requireNonNull(domain);
this.name = requireNonNull(name);
this.description = requireNonNull(description);
}
So my question is, do we even need to annotate when using java 8?
Edit: I found out later that some consider a bad practice to use Optional
in arguments, there is a good discussion with pros and cons here Why should Java 8's Optional not be used in arguments
Recommended option given that it is not best practice to use Optional in arguments, we need 2 constructors:
//Non null description
public Role(UUID guid, String domain, String name, String description) {
this.guid = requireNonNull(guid);
this.domain = requireNonNull(domain);
this.name = requireNonNull(name);
// description will never be null
requireNonNull(description);
// but wrapped with an Optional
this.description = Optional.of(description);
}
// Null description is assigned to Optional.empty
public Role(UUID guid, String domain, String name) {
this.guid = requireNonNull(guid);
this.domain = requireNonNull(domain);
this.name = requireNonNull(name);
this.description = Optional.empty();
}