Possible Duplicate:
How to avoid “!= null” statements in Java?
Share your thoughts..
Possible Duplicate:
How to avoid “!= null” statements in Java?
Share your thoughts..
A first answer is to always return empty Lists, Sets, Arrays instead of null for method returning this kind of objects. Item 43 of Effective Java second edition from Joshua Bloch
Take a look at the Null Object Pattern. The basic idea is you have a special version of your class that you can use instead of null.
This special version has fields set to default values that make sense in your code. It means that you never have null references, you just have a class that doesn't do much or returns default values when used.
In my opinion, null checks are evil. They show that there is no contract that establishes whether obj
may be null
or not. The good alternative would be to write the code in such a way that obj
is guaranteed never null
. For example: if a getter must get a non-null
obj
, but cannot, it must throw an exception itself.
if (CONST_VALUE.equals(obj)) { ... }