Null object pattern

Null pointer
Null pointer

The use of the return to null on a method or function is quite normal when you are programming. (or nil depends on your programing language). There is a pattern called Null Object Pattern that could help you avoid this kind of returning and improve your design for a different state and behavior for the situation where your object is null.

Some days ago I was working on a simple application which read a text file and transforms each line in a command to be executed. So when it finds a line that couldn’t be converted to a valid command the method had returned null.

I have a single method “run” to perform all this commands.

public void run(){
List<Command> allCommands = buildFrom(new File(“actions”));

for (Command command : allCommands){
if (command != null)  command.execute();


Note that there is a condition check if the command is null or not and then not throw any NullPointerException, I could check the nullability on buildFrom and just return the commands not null. But instead I’ve created a NullCommand that just shows to user what command won’t be perfomed.

public void execute(){
log(“The action “+action+” won’t be perfomed: Invalid action!”);

There is an important consideration: the over (and wrong) use of this pattern can lead you to think that errors or bugs are part of the normal flow of program. In my case it was usefull because I show the message for user informing him so he can edit the text file and fix the error (mistyping, grammar, whatever) and then run it again. The next time you think in return null consider the use of this pattern.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s