Design pattern “to do nothing” a.k.a NullObjectPattern

Its been some time since i blogged, Thanks to my schedule , recently i was just going through some of the Design Patterns and this one stuck me hard. Yes, Design Pattern to do nothing! well how many times have we seen our code getting bombed due to the NPE a.k.a NullpointerException, or in other words how bad our code looks with “if conditions” to check if any of the objects are NULL. our code gets cluttered with these conditions to avoid NPE’s . NullObjectPattern is a pattern to avoid such a mishap in your code.

So what is this NullObjectPattern all about? Well, the author of this pattern Bobby Woolf feels that the solution lies in determining the earliest point which the reference could be NULL, and stifle it . so how to do all this?

Here is the example.

public List getList(String command){

if(command.equals(“A”)){return new ArrayList().add(“A”);}

if(command.equals(“B”)){return new ArrayList().add(“B”);}

if(command.equals(“C”)){return new ArrayList().add(“C”);}

else{ return null;}

//used as follows.
List listObj = getList();

//Do some thing after checking listObj for null.

Using NullObjectPattern

Everything remains same but only this “else{ return null;}” changes as follows

“else{ return null;}” gets changed to “else{ return new NullList();}”

public class NullList implements List(){

public void someMethod(){

logger.debug(“This Object is pointing to the null reference!”);

}
}

Kitchen Sink!

I was just trying lots of stuff, in that process did learn some interesting things. tried out antlr , its an interesting tool for language grammar similar to Lex & Yacc . It has a simple editor called antlrworks, its a good tool with all basic features like, console, debugger,stack, Syntax diagram. Again the problem is that, there is lack of documentation. Version3 and version2 has some significant differences. Unfortunately, in India The definitve ANTLR Reference is not available . I am on a hunt to get some proper book, so its a bumpy ride till i get hold of it.I had mentioned in my previous post about the lack of tools for Groovy , the good news is that Geertjan has been working on the plugin for the netbeans 6.0, The best part about this is that, he is documenting each and every step on his blog. I have been following it and building an plugin for groovy, Its still not complete though, its taking a good shape. The net beans 6.0 rocks! i must say it again and again.. The Generic Language Framework(project Schliemann) is really an amazing stuff, can build the netbeans module supporting your language of interest very easily with a declarative Language. The language syntax is similar to the EBNF , can define lexical structure of your language tokens by regular expressions ;-)