Good programming practices

anti-if

Replace null with Null Object

December 18th, 2011

Dealing with possible null pointers often require to use “if” statement. To help programmers in those situations, I wrote a utility class which returns some default object, if null will appear. Usage is very simple – just wrap a possible null with an appropriate method from this class and you can use a variable without fear of NullPointerException. This is example of Null Object design pattern. More…

Iterating over non null elements only

October 27th, 2011

Since Java 5 in this language exists very useful “foreach” statement. But if collection contains null elements, iterator will also return null. If code doesn’t check against null, this may cause a NullPointerException. So I made a simple class based on Decorator Design Pattern. It just wraps an Iterable or Iterator and return only non null values. More…

New java.util.Objects class will help in everyday code

July 25th, 2011

Java 7 is coming, so it’s worth to see how the new version helps to create clearer code. Here I present some simple but very useful methods of java.util.Objects class. All those methods are static, so you don’t have to create a new object. Using them it’s easy reduce “if” statements or conditional expressions. The following examples show an old and a new code. More…