且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不在OOP设计中使用instanceof运算符?

更新时间:2023-11-14 08:59:40

instanceof 只需打破开放/关闭原则和/或 Liskov替代原则



如果由于 instanceof 使用情况我们不够抽象,每次新的子类进入,可能会更新收集应用程序逻辑的主要代码。
这显然不是我们想要的,因为它可能会破坏现有的代码并降低其可重用性。



因此,应该优先使用多态超过基本使用条件。


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 heavy operation, but it seems that, at least java, handles it pretty well (even more efficiently than Object.toString() comparison).

Can someone please explain, or direct me to some article which explains why is it a bad design?

Consider this:

Class Man{
  doThingsWithAnimals(List<Animal> animals){
    for(Animal animal : animals){
      if(animal instanceOf Fish){
        eatIt(animal);
      }
      else if(animal instanceof Dog){
        playWithIt(animal);
      }
    }
  }
  ...
}

The decision of what to do with the Animal, is up to the Man. Man's desires can also change occasionally, deciding to eat the Dog, and play with the Fish, while the Animals don't change.

If you think the instanceof operator is not the correct OOP design here, please tell how would you do it without the instanceof, and why?

Thanks.

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.