21.

Hybrid Patterns

Before leaving this topic, I'd like to discuss two more possible implementations, each a kind of cross between the two implementations I've discussed. In these hybrid implementations, no impostor types are used, but the code has many of the same susceptibilities to error that would be present if they were. Here's the first:

Although the compiler would still catch type misspellings and the types of objects could not be changed, we are again using an if-then-else block to dispatch on the appropriate type. Therefore, we are again susceptible to mismatches between the instanceof checks in the if-then-else block and the set of types we are operating on.

The second hybrid implementation is similar to the first. It also uses separate classes to represent the variants, and defines the area function in each variant, but adds a numeric tag to each variant. The tags are included so that switch statements can be used to write procedural code to process the variants (instead of using a visitor). This approach is susceptible to mismatches in procedural code to process the variants. Some programmers implement their code this way because they believe it's faster than using dynamic dispatch. In practice, however, this technique rarely results in a noticeable performance improvement. But it does result in an increased likelihood of error.

I should also mention that neither hybrid implementation is as extensible as the solution in Listing 15-3.

Listing 15-3: Implementation of Forms with Real Types

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



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