84.

What We've Learned

In this chapter on the Run-On Initializer bug pattern we've learned the following:

  • This bug is caused by class definitions in which the class constructors don't take enough arguments to properly initialize all the fields of the class.

  • A potential error: The programmer writing the initialization code may forget to put in one of the initialization steps.

  • Another potential error: There may be an order-based dependence in the initialization steps, unknown to the programmer, who therefore executes the statements out of order.

  • Yet another error: The class being initialized might change. New fields might be added, or old ones removed.

  • A sure prevention: It's much better to define constructors that initialize all fields.

  • If you encounter legacy code infected with this bug, often the best thing to do is to throw out that legacy code and start fresh!

  • However, when you must work with a legacy codebase in which a class doesn't initialize all of its fields in the constructors, you may not want to modify the constructor signatures, especially if the unit tests over the code are scant.

  • When you must work with legacy code, attempt to control the errors by (1) initializing the fields to non-null, default values; (2) including extra constructors; (3) including an isInitialized() method in the class; and (4) constructing special classes to represent the default values.

  • A good practice is to fill in the fields with default values; you help to ensure that instances of your class will be in a well-defined state at all times.

  • Remember, gratuitous uses of null values inevitably result in NullPointerExceptions—and those are bad.

  • Include additional constructors. You can use them in new contexts where you don't have to include new run-on initializations.

  • An isInitialized() method in the class will allow for quick determination as to whether an instance has been initialized.

  • Construct special classes to represent the default values. The advantage is that you'll be constantly reminded with compiler errors (at every point in the code where you forgot to cast) that this method call doesn't work on the default value. The disadvantage: a performance hit each time the field is accessed (as a cast is needed).

  • There's never a good reason to include a constructor for a class that leaves any of the fields uninitialized.

In Chapter 20 we'll take a look at group of bugs that cluster around a single issue, that of platform dependence.



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