Fail-fast assertions in Java
I make no claims for being the sole originator of this pattern, but if like me you tire of digging through Java code hunting for the source of NullPointerExceptions, you may want to adopt a "fail fast" approach and check arguments for unexpected null values at the first opportunity. Here's a trivial little helper method that makes use of generics to add a bit of syntactic sugar to the process:
privateT assertNotNull(T potentiallyNullObject) throws Error {
if (potentiallyNullObject == null)
throw new Error("Unexpected null "+potentiallyNullObject.getClass()+" found.");
return potentiallyNullObject;
}
You could enhance the method by adding an extra argument to customise the Error message on a per-assertion basis, if you wanted. The advantage of generification is that you can wrap the assertion round the first reference to an argument in your method, rather than explicitly checking each argument at the start of the method. (Although that's an equally valid approach.)
As an example, here's a method that adds a String to a class List member. The assertNotNull method enforces the contract that objects added to the list may not be null:
public void addListItem(String newListItem) {
myList.add(assertNotNull(newListItem));
}
I hope the benefits of this approach are obvious!
Write reply
This item is closed, it's not possible to add new comments to it or to vote on it
Comments must be approved before being published. Thank you!