title: Avoiding instanceof in Java
body: <p>Having a chain of "instanceof" operations is considered a "code smell".  The standard answer is "use polymorphism".  How would I do it in this case?</p>
  
  <p>There are a number of subclasses of a base class; none of them are under my control.  An analogous situation would be with the Java classes Integer, Double, BigDecimal etc.</p>
  
  <pre><code>if (obj instanceof Integer) {NumberStuff.handle((Integer)obj);}
  else if (obj instanceof BigDecimal) {BigDecimalStuff.handle((BigDecimal)obj);}
  else if (obj instanceof Double) {DoubleStuff.handle((Double)obj);}
  </code></pre>
  
  <p>I do have control over NumberStuff and so on.</p>
  
  <p>I don't want to use many lines of code where a few lines would do.  (Sometimes I make a HashMap mapping Integer.class to an instance of IntegerStuff, BigDecimal.class to an instance of BigDecimalStuff etc.  But today I want something simpler.)</p>
  
  <p>I'd like something as simple as this:</p>
  
  <pre><code>public static handle(Integer num) { ... }
  public static handle(BigDecimal num) { ... }
  </code></pre>
  
  <p>But Java just doesn't work that way.</p>
  
  <p>I'd like to use static methods when formatting.  The things I'm formatting are composite, where a Thing1 can contain an array Thing2s and a Thing2 can contain an array of Thing1s.  I had a problem when I implemented my formatters like this:</p>
  
  <pre><code>class Thing1Formatter {
    private static Thing2Formatter thing2Formatter = new Thing2Formatter();
    public format(Thing thing) {
        thing2Formatter.format(thing.innerThing2);
    }
  }
  class Thing2Formatter {
    private static Thing1Formatter thing1Formatter = new Thing1Formatter();
    public format(Thing2 thing) {
        thing1Formatter.format(thing.innerThing1);
    }
  }
  </code></pre>
  
  <p>Yes, I know the HashMap and a bit more code can fix that too.  But the "instanceof" seems so readable and maintainable by comparison.  Is there anything simple but not smelly?</p>
  
  <p>Note added 5/10/2010:</p>
  
  <p>It turns out that new subclasses will probably be added in the future, and my existing code will have to handle them gracefully.  The HashMap on Class won't work in that case because the Class won't be found.  A chain of if statements, starting with the most specific and ending with the most general, is probably the best after all:</p>
  
  <pre><code>if (obj instanceof SubClass1) {
      // Handle all the methods and properties of SubClass1
  } else if (obj instanceof SubClass2) {
      // Handle all the methods and properties of SubClass2
  } else if (obj instanceof Interface3) {
      // Unknown class but it implements Interface3
      // so handle those methods and properties
  } else if (obj instanceof Interface4) {
      // likewise.  May want to also handle case of
      // object that implements both interfaces.
  } else {
      // New (unknown) subclass; do what I can with the base class
  }
  </code></pre>