The idiom I use the most when programming in Java is to test if object != null before I use it. This is to avoid a NullPointerException. I find the code very ugly and it becomes unreadable.
Is there a good alternative to this?
Update: Pan, I was not clear with my question. I want to address the necessity to test every object if you want to access a field or method of this object. For example:
...
if (someobject != null) {
someobject.doCalc();
}
...
In this case I will avoid a NullPointerException, and I don't know exactly if the object is null or not. So my code get splattered with these tests.
Anonymous User
02-May-2015public class MyParser implements Parser {private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
Compare:
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
public Action findAction(final String userInput) {/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}