Is instanceof considered bad practice? If so, under what circumstances is instanceof still preferable?

aioobe picture aioobe · May 1, 2010 · Viewed 36.9k times · Source

Over the years, I've tried to avoid instanceof whenever possible. Using polymorphism or the visitor pattern where applicable. I suppose it simply eases maintenance in some situations... Are there any other drawbacks that one should be aware of?

I do however see it here and there in the Java libraries so I suppose it has its place? Under what circumstances is it preferable? Is it ever unavoidable?

Answer

Alexander Pogrebnyak picture Alexander Pogrebnyak · May 1, 2010

It's definitely has its place in a stock implementation of equals. E.g.

public boolean equals ( Object o )
{
  if ( this == o )
  {
     return true;
  }

  if ( ! (o instanceof MyClass) )
  {
    return false;
  }

  // Compare fields
  ...
}

One neat thing to know about instanceof is that its LHS can be null and in that case the expression evaluates to false.