16.

Overview

When you get a NullPointerException and you suspect that class-definition constructors don't take enough arguments to initialize all the class's fields, you may be looking at the Run-On Initializer pattern. We discuss initializing all constructor fields with special classes and including multiple constructors.

For various reasons, mostly bad, you will often see class definitions in which the class constructors don't take enough arguments to properly initialize all the fields of the class. Such constructors require client classes to initialize instances in several steps (setting the values of the uninitialized fields) rather than with a single constructor call.

Initializing an instance in this way is an error-prone process that I refer to as a Run-On Initialization. The types of bugs that result from this process have similar symptoms and remedies, so we can group them together into the Run-On Initializer bug pattern.

Here is this pattern in a nutshell:

  • Pattern: Run-on Initializer.

  • Symptoms: A NullPointerException at the point that one of the uninitialized fields is accessed.

  • Cause: A class whose constructors don't initialize all fields directly.

  • Cures and Preventions: Initialize all fields in a constructor. Use special classes for default values when better values can't be used. Include multiple constructors to cover cases where better values can be used. When your hands are tied, at least include an isInitialized() method.



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