Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 343
Luke Taylor Avatar asked Apr 01 '26 14:04

Luke Taylor


1 Answers

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;
  }
}
like image 146
Reverend Gonzo Avatar answered Apr 03 '26 03:04

Reverend Gonzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!