29/08 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:


private T 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!

29/03 Active Record for Java programmers

There's a good article over at IBM developerWorks on Active Record - one of the core features of Ruby on Rails. I like it for two main reasons - firstly, it has a pretty strong "there is no one true language - get over it" message, and secondly, the idea of actually learning from the strengths of other languages rather than dissing them appeals to me. It's the first of a series of articles by Bruce Tate themed around that latter point, and I look forward to reading the rest.