次のコードがあるとします。
public boolean doesElfLikeIt ( Monster mon )
{
if ( mon instanceof Orc ) { return false; }
if ( mon instanceof Elf ) { return true; }
}
これは良いプログラミング アプローチですか、それとも次のような方法を使用する必要があります。
public boolean doesElfLikeIt ( Monster mon )
{
if ( mon.getType() == Orc.type ) { return false; }
if ( mon.getType() == Elf.type ) { return true; }
}
私がこれを尋ねている理由は、instanceof
比較がどれほど悪いかについてよく耳にするからですが、私はそれが役に立つと思います.