Is it good practice to often use instanceof?

前端 未结 6 1309
北海茫月
北海茫月 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 11:55

    IMHO using instanceof is a code smell. Simply put - it makes your code procedural, not object oriented. The OO way of doing this is using the visitor pattern.

    enter image description here

    The visitor pattern also allows you to easily build decorators and chain of responsibility on top of it, thus achieving separation of concerns, which results in shorter, cleaner and easier to read and test code.

    Also do you really need to know the exact class ? Cant you take advantage of polymorphism ? After all Axe IS a Weapon just as Sword is.

提交回复
热议问题