Getting rid of the nulls in your life

There's nothing so annoying as having written some pretty cool code, but then somewhere in the surrounding code suddenly a nullpointer exception appears.

Nullpointers are evil, I think that's pretty clear, but you as a developer can actually reduce the amount of possible nullpointers!

From the experience in projects I've worked on, it helps to:


1. Use final (immutable) fields on your class where possible. For hibernate entities this is often not possible or very inconvenient, but in other classes this prevents accidentally setting the field to null.


2. Apply the 'fail early'  principle. Don't let the troubles of inner components affect the outer ones. If bad things happen that cannot be resolved, such as invalid input on one of the public methods at the component, it usually means throwing a runtime exception. Don't just return null and make others do the dirty work.


3. Always describe the null case for non primitive return types on methods, in javadoc. If a method needs to return null, it is probably meaningful and worth to explain. If it never does, just say so. Clients of the component can then safely assume that the return value is nullpointer safe.

More reading:


Reactie schrijven

Commentaren: 0