I want to fail fast when arguments passed into my method are null.
Use a common null check method to fail fast when input arguments are null.
This example is explicitly checking if the employee instance and throwing the NullPointerException to quickly fail the method call.
There are several utility classes that can implement this logic for you. Both Java 8 and Google Guava include an Objects class that encapsulates and exposes this logic in different ways.
However, my preferred solution is to use the Lombok framework's @NonNull annotation. If you are not using Lombok get on-board…and stop bellyaching about how Java is so verbose!
This is what it looks like:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void generatePaycheck(@NonNull Employee employee) { | |
// do paycheck stuff ... | |
} |
With the Java 8 Objects class the following checks are possible. Note, I did a static import on the Objects class - I believe this improves the readability of the code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.util.Objects.requireNonNull; | |
... | |
// throws a NullPointerException when null | |
requireNonNull(employee); | |
// throws a NullPointerException with a message | |
requireNonNull(employee, "employee reference is null"); | |
// throws a NullPointerException with a message from a supplier function | |
requireNonNull(employee, () -> errorMsgProducer.getNullMessage("employee")); | |
// do paycheck stuff ... |
If it is a private method do you really need the null check?
Why are you processing null references in the first place?
No comments:
Post a Comment