69.

What We've Learned

In this chapter on the Impostor Type bug pattern, we've learned the following:

  • Impostor Types occur when special tags in fields are used to distinguish between types of objects; errors are possible when a tag mislabels the associated data.

  • One common symptom of an Impostor Type is that many conceptually distinct types of data are all treated in the same, incorrect, manner when the program is run.

  • Another common symptom is that data doesn't match any of the designated types.

  • Suspect the Impostor Type whenever there is a mismatch between the conceptual type of data and the way it is handled by a program.

  • Using real types (as opposed to special tags) means that our type checker would signal an error on any new instance that is entered incorrectly; it would also remind us to define methods for our subclasses.

  • There are hybrid implementations that may appear to be solutions but aren't. They don't employ Impostor Types, but they do use if-then- else blocks (or switch blocks) to dispatch on the appropriate type. They make us susceptible to mismatches between the cases in the block and the set of types we're using. (See Listing 15-4.)

    Listing 15-4: A Cross-Breed Implementation

    start example
     public abstract class Form {   double scale;   public Form(double _scale) {     this.scale = _scale;   } public double getArea() {  if (this instanceof Square) {     return scale * scale;   }   else if (this instanceof Circle) {    return Math.PI * scale * scale;   }   else { // this instanceof Triangle     return scale * (scale * Math.sqrt(3) / 4);    }   } } class Square extends Form {  public Square(double _scale) {   super(_scale);   } } class Circle extends Form {  public Circle(double _scale) {   super(_scale);   } } class Triangle extends Form {  public Triangle(double _scale) {   super(_scale);   } } 
    end example

  • One of the advantages of the Java language is that it is strongly typed, so that the possibility of a type error is eliminated before a program is run.

The most important point in this chapter is that the language offers you the best resources for avoiding this type of error—the static type system. Just remember to use it.

In Chapter 16, we'll examine the Split Cleaner, an instance in which code doesn't manage resources properly by freeing them up when finished as it should.



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