null object pattern and eliminating NullPointerExceptions

Since we released 3.1.0-beta3, we’ve had a flood of bug reports, quite a
few of which have been due to NullPointerExceptions, and most of which
are not new. That is, they’re bugs which date back to 3.0 or before, but
no one told us about them.

Usually these are due to simple coding mistakes, like calling getMap()
and then not checking whether the Map is null before calling a method
on it. It occurred to me this morning while investigating one of these
bugs that we could avoid all such problems by using the Null Object
pattern:

en.wikipedia.org/wiki/Null_Object_pattern

What this would amount to in the case of Map is returning a static Map
where all of the methods are overridden to be no-ops. (That’s not ideal,
as it would be better to have Map be an interface and have both the
real Map and NullMap implement it, or have NullMap be a superclass of
Map, but it would work.) As an added bonus, we could stip out the hundreds
of places where we test whether a returned Map is null.

Well, there’s real semantic meaning to having getMap() return null – it means the piece is sitting in the palette and hasn’t been placed yet. Many traits check for null because what they do doesn’t make sense if the piece hasn’t been placed. So if you use a null object pattern, you’ll end up having to replace many of the ‘getMap() != null’ checks with ‘getMap() != Map.NO_MAP’ checks. Using a null object amounts to silently swallowing all those cases where the code expected to find a real map and didn’t. We could end up missing a lot of bugs this way.

rk

Post generated using Mail2Forum (mail2forum.com)