Tutorial :What's the best way to avoid lots of “if (obj != null)” in Java code? [duplicate]



Question:

Possible Duplicate:
How to avoid “!= null” statements in Java?

Share your thoughts..


Solution:1

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


Solution:2

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.


Solution:3

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.


Solution:4

Yoda Conditions

if (CONST_VALUE.equals(obj)) { ... }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »