Search code examples
javainstanceof

Java: instanceof or custom getType


Assuming I have the following code:

public boolean doesElfLikeIt ( Monster mon )
 {
    if ( mon instanceof Orc ) { return false; }
    if ( mon instanceof Elf ) { return true; }

 }

Is this a good programming approach or should I rather go for something like this:

public boolean doesElfLikeIt ( Monster mon )
 {
    if ( mon.getType() == Orc.type ) { return false; }
    if ( mon.getType() == Elf.type ) { return true; }

 }

The reason why I'm asking this is because I hear a lot about how evil the instanceof comparison is, however I find it useful.


Solution

  • Neither. What you really should be doing is something like:

    class Monster {
      public abstract boolean likesElves();
    }
    
    class Orc extends Monster {
      public boolean likesElves() {
        return false;
      }
    }
    
    class Elf extends Monster {
      public boolean likesElves() {
        return true;
      }
    }