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
+6
A:
Manuel Selva
2010-07-29 14:33:20
Effective Java Item 43. +1.
Mark Peters
2010-07-29 14:36:41
@Mark Yep, I updated my answer while you where writing your comment ;-)
Manuel Selva
2010-07-29 14:38:16
Totally agree, readability is severely impaired. But this is an idiom which you should be familiar with, and not afraid to use on occasion.
Yuval A
2010-07-29 14:40:08
+2
A:
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.
Vlad
2010-07-29 14:36:16
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 b
2010-07-29 14:43:18
@matt: indeed. however the check for null can be done not before using the object, but immediately after getting it.
Vlad
2010-07-29 15:28:24
+4
A:
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.
Matt Warren
2010-07-29 14:36:33
+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.
Carl Manaster
2010-07-29 14:39:40
Although good in some situations, I find it is fairly limited in real world usage.
Robin
2010-07-29 14:42:34
@Robin, yeah it has some limits, but it does beat getting NullReferenceExceptions!!
Matt Warren
2010-07-29 16:11:27