Why not use instanceof operator in OOP design?

前端 未结 4 1818
一整个雨季
一整个雨季 2020-11-28 12:33

It has been repeatedly said that the instanceof operator should not be used except in the equals() method, otherwise it\'s a bad OOP design.

Some wrote that this is a

4条回答
  •  悲哀的现实
    2020-11-28 12:44

    instanceof simply breaks the Open/Close principle. and/or Liskov substitution principle

    If we are not enough abstract because of instanceof usage, each time a new subclass makes an entrance, the main code gathering the logic of the application might be updated. This is clearly not what we want, since it could potentially break the existing code and reduce its reusability.

    Therefore, a good usage of polymorphism should be preferred over the basic use of conditional.

提交回复
热议问题