Java Reference
In-Depth Information
Listing 10.3. Null -safe attempt 2: too many exits
In this second attempt, you try to avoid the deeply nested if blocks, adopting a different strategy:
every time you meet a null variable, you return the string “Unknown.” Nevertheless, this
solution is also far from ideal; now the method has four distinct exit points, making it hardly
maintainable. Even worse, the default value to be returned in case of a null, the string
“Unknown,” is repeated in three places—and hopefully not misspelled! Of course, you may wish
to extract it into a constant to avoid this problem.
Furthermore, it's an error-prone process; what if you forget to check that one property could be
null? We argue in this chapter that using null to represent the absence of a value is the wrong
approach. What you need is a better way to model the absence and presence of a value.
10.1.2. Problems with null
To recap our discussion so far, the use of null references in Java causes both theoretical and
practical problems:
It's a source of error. NullPointerException is by far the most common exception in Java.
It bloats your code. It worsens readability by making it necessary to fill your code with often deeply
nested null checks.
It's meaningless. It doesn't have any semantic meaning, and in particular it represents the wrong way
to model the absence of a value in a statically typed language.
It breaks Java philosophy. Java always hides pointers from developers except in one case: the null
pointer.
 
Search WWH ::




Custom Search