Is it good practice to often use instanceof?

前端 未结 6 1308
北海茫月
北海茫月 2020-12-14 11:44

The scenario. I\'m writting game-related code. In that game a Player(its also a class) has a list of Item. There are other types of items that inhe

6条回答
  •  攒了一身酷
    2020-12-14 12:11

    I don't necessarily think instanceof is bad for coders who know what they are doing and use it to avoid having to write more complicated code to get around it. There is a use for everything, and also a mis-use.

    With that said, the description you provide does not require instanceof. There are various ways you can implement this without instanceof, and (the most important thing) the alternate solution must be better than using instanceof. Don't just go with a non-instanceof solution to avoid instanceof because you heard it is bad.

    I think that for your scenario an non-instanceof solution has benefits in making the solution more easily extensible.

    for (Item i: items) {
        if (ItemTypes.WEAPON_ITEM.equals(i.getType)) {
            processWeaponType(i);
        }
    
    }
    

    or

    for (Item i: items) {
        if (WeaponItem.class.equals(i.getType)) {
            processWeaponType(i);
        }
    
    }
    

提交回复
热议问题