Wednesday, September 06, 2006

Static Checking

There are many things a compiler does which helps a programmer. Let me give an example of my recent experience

String name;
if (i == 0) {
name = getName();
if (name.equals("x")) {
doSomething();
}
} else {
name = getAnotherName();
if (name.equals("y")) {
doAnotherThing();
}
}


this is perfectly okay .. if we had forgotten the call name=getAnotherName() in the else condition, compiler would crib saying that name is not initialized.

Now in many code i see that people have a tendency to declare
String name = null;

in this case if you had forgotten to call name=getAnotherName() in else, the compiler would pass as name is initialized to null. And at runtime you will get a NullPointerException as you are doing null.equals("y")

In some places initializing to null cannot be avoided, but i believe, wherever possible dont initialize to null, it will help you

1 comment:

perseus said...

good tip :)