Do you see your code throws NullPointerException at run time? because error causes from this

someObject.getSomething()

then you found you forgot to write defencive NULL check,

if (null == someObject) {
throw new IllegalArgumentException(“can’t handle null parameter!”);
}

someObject.getSomething();

The issue is you have to implement all your code for that. Repeating such null logic in one or two places in a system isn’t a problem, but repeating it in multiple places bloats a system with unnecessary code. Compared with code that is free of null logic, code that is full of it generally takes longer to comprehend and requires more thinking about how to extend. Null logic also fails to provide null protection for new code. So if new code is written and programmers forget to include null logic for it, null errors can begin to occur.

How to implement Null Object? here is some tips:

1. Refactor to Null Object pattern [original]

2. Null Object Design Pattern

3. Implementing the Null Object Pattern using AOP

4. Using Java’s Dynamic Proxy to introduce Null object

5. Implement Design by Contract for Java using dynamic proxies

[update]

07-11-2007:  beware of Defensive Null Checking 

Advertisements