6

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

Share your thoughts..

1

4 Answers 4

20

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

Sign up to request clarification or add additional context in comments.

4 Comments

@Mark Yep, I updated my answer while you where writing your comment ;-)
Link is no longer active, just leads to the Java technetwork site
@ManuelSelva Broken Link
@GC_ Fixed, thank you.
5

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.

3 Comments

+1. Empty collections are almost a special case of this - you just don't need to write a class for them. But the pattern of handing around something that isn't null and behaves safely is the same.
Although good in some situations, I find it is fairly limited in real world usage.
@Robin, yeah it has some limits, but it does beat getting NullReferenceExceptions!!
4

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.

3 Comments

On the other hand, for many contracts, null is an acceptable value. So you wouldn't want to eliminate ever checking for null, only eliminate the defensive need to check everything.
@matt: indeed. however the check for null can be done not before using the object, but immediately after getting it.
exactly. If null checks are everywhere in the code, it shows that the code is poorly written.
1

Yoda Conditions

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

5 Comments

While very effective, that does impair readability some.
Totally agree, readability is severely impaired. But this is an idiom which you should be familiar with, and not afraid to use on occasion.
it also hides potential null pointer exceptions which can be bad
@OliverWatkins why? By using the equals(Object) method of the CONST_VALUE object, it will never throw a NPE (assuming that the CONST_VALUE is a, well, constant that's already been initialized)
yes it they are constants it should be fine. But it reads badly : obj.equals(CONST) reads far better than CONST.equals(obj)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.