avoid instanceof in Java

前端 未结 9 2260
清歌不尽
清歌不尽 2021-02-12 20:40

I have been told at some stage at university (and have subsequently read in upteen places) that using instanceof should only be used as a \'last resort\'. With this

9条回答
  •  粉色の甜心
    2021-02-12 21:05

    You could declare setUITweenManager in GameObject with an implementation that does nothing.

    You could create an method that returns an iterator for all UITweenable instances in array of GameObject instances.

    And there are other approaches that effectively hide the dispatching within some abstraction; e.g. the Visitor or Adapter patterns.


    ... have I committed some cardinal sin of OOP somewhere along the line that has me using instanceof here?

    Not really (IMO).

    The worst problem with instanceof is when you start using it to test for implementation classes. And the reason that is particularly bad is that it makes it hard to add extra classes, etcetera. Here the instanceof UITweenable stuff doesn't seem to introduce that problem, because UITweenable seems to be more fundamental to the design.


    When you make these sorts of judgement, it is best to understand the reasons why the (supposedly) bad construct or usage is claimed to be bad. Then you look at you specific use-case and make up whether these reasons apply, and whether the alternatively you are looking at is really better in your use-case.

提交回复
热议问题