|
UseNullable
Use @NullableTo eliminate NullPointerExceptions in your codebase, you must be disciplined about null references. We've been successful at this by following and enforcing a simple rule: Every parameter is non-null unless explicitly specified.The Guava: Google Core Libraries for Java and JSR-305 have simple APIs to get a nulls under control. Preconditions.checkNotNull can be used to fast-fail if a null reference is found, and @Nullable can be used to annotate a parameter that permits the null value: import static com.google.common.base.Preconditions.checkNotNull;
import static javax.annotation.Nullable;
public class Person {
...
public Person(String firstName, String lastName, @Nullable Phone phone) {
this.firstName = checkNotNull(firstName, "firstName");
this.lastName = checkNotNull(lastName, "lastName");
this.phone = phone;
}Guice forbids null by default. It will refuse to inject null, failing with a ProvisionException instead. If null is permissible by your class, you can annotate the field or parameter with @Nullable. Guice recognizes any @Nullable annotation, like edu.umd.cs.findbugs.annotations.Nullable or javax.annotation.Nullable. | |
► Sign in to add a comment
I finally downloaded a suitable jar meeting JSR 305 containing annotations which played nicely with this feature from...
http://mirrors.ibiblio.org/pub/mirrors/maven2/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar
...although future downloaders should probably check for newer versions.
If you use maven, the above jar file is in maven central.
<dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <version>1.3.9</version> </dependency>