33.

Robustness vs. Lack of Diagnostic Evidence

Before we leave this topic, let's address the concerns of the programmers who use null flags regularly. Programmers often argue that the use of null flags makes their programs more "robust." After all, a robust system handles varied situations gracefully rather than throwing exceptions at every little problem that comes up.

Handling Exceptions in the Best Place

What this argument overlooks is the fact that exceptions are a great tool to increase the robustness of code by allowing control to pass quickly during an exceptional condition to the place most appropriate for controlling it. The use of null flags, on the other hand, limits control flow to the ordinary paths of method invocation and return-until the whole program crashes, of course.

Additionally, by using null flags in this way, the programmer effectively buries the evidence of where the exceptional condition occurred. Who knows how far that null pointer was passed from method to method before it was dereferenced? This simply makes it harder to diagnose errors and determine how to fix them.

Note 

Exceptions are a great tool to increase the robustness of code. During an exceptional condition, they allow control to quickly pass to the best place to handle the exception.

Experience shows that code breaks often. Our primary concern should be to avoid such obfuscation and make the diagnosis as easy as possible. Therefore, as a matter of principle, I try to write code that signals exceptional conditions as soon as possible and attempts to recover only from exceptional conditions that do not indicate bugs in the program.

And What About Legacy Code?

Even if you try to avoid using null flags in your own code, you will inevitably have to deal with legacy code that uses them. In fact, many of the Java library classes themselves, such as the Hashtable and BufferedReader classes that we used earlier in this chapter, use null flags.

When maintaining such classes, make sure that it is made clear to all clients that the null value is reserved as a flag; it should never be returned under ordinary circumstances (e.g., as the stored value of a key in a Hashtable). When using such classes, you can avoid bugs by explicitly checking whether an operation will return null before performing it. For example, with Hashtables, I always test with containsKey() before calling get(). Such preventative measures can go a long way in eliminating occurrences of this pattern.



Bug Patterns in Java
Bug Patterns In Java
ISBN: 1590590619
EAN: 2147483647
Year: N/A
Pages: 95
Authors: Eric Allen

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net