44.

What We've Learned

In this chapter on the Double Descent bug pattern, we've learned the following:

  • If a ClassCastException is thrown as your program recursively descends a composite data structure, it usually means that a method call isn't dispatching appropriately on the second call.

  • One cure is to factor out casting code into separate methods for each class.

  • Another cure is to examine the invariants to ensure that the casts will succeed.

  • Another is to wrap each cast in an instanceof check. However, I suggest you avoid instanceof checks. Otherwise, you'll have to revise them every time you add another subclass of Tree.

  • Instead of instanceof checks, try adding extra methods to the subclasses to perform the appropriate actions for each subclass. This makes use of the polymorphic aspect of object-oriented languages, one of such languages' advantages.

  • A quick fix seems to be to get rid of the Leaf class and represent the Leaf nodes as null values in Branch's left and right fields. But this "fix" would introduce a Dangling Composite. The runtime error would throw a NullPointerException instead of a ClassCastException, a harder exception to diagnose.

  • Commenting in code is helpful to logical debugging, especially for else clauses. (See the sidebar "Comments in Code" in this chapter.)

  • Holding each cast to this level of scrutiny—knowing that the invariants will ensure that any casts will succeed—will lead you to eliminate many such casts.

In short, the moral to this story is to always convince yourself that the invariants inside a code block ensure that any casts in the block will always succeed. When each cast is held to this level of scrutiny, you may find yourself eliminating many of these casts by adding methods to the relevant subclasses.

In Chapter 12, we'll discuss the Liar View bug, a pattern that often occurs in GUI applications.



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