avoid instanceof in Java

前端 未结 9 2258
清歌不尽
清歌不尽 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:06

    The problem with this approach is that it doesn't usually appear at one place only in your code and thus makes it more or less painful to add another implementations of the interface in the future. Whether to avoid it depends on your consideration. Sometimes YAGNI can be applied an this is the most straightforward way.

    Alternatives had been suggested by others, for example the Visitor pattern.

提交回复
热议问题