mardi 15 novembre 2022

Avoiding the use of instanceOf

I have an abstract class with several childs. I want 4 of them to be able to do a thing which the parent class cannot do. What I have implemented so far would be something like this:

Parent class:

  abstract class Parent {
      
      abstract void doSomething();
  }

Intermediate parent class:

  abstract class IntermediateParent extends Parent {

      abstract void performAction();
  }

Some of the concrete classes:

  class ConcreteClass extends Parent {

      @Override
      protected void doSomething() {
          //do something
      }
  }

The other four concrete classes:

 class ChildConcreteClass extends IntermediateParent {

      @Override
      protected void doSomething() {
          //do something
      }

      @Override
      protected void performAction() {
          //perform action
      }
  }

But now, I found myself in this situation.

Class that triggers the call:

     Parent parent = getParent();
     if(class instanceof ChildConcreteClass){
         ChildConcreteClass childConcreteClass = (ChildConcreteClass) parent;
         childConcreteClass.performAction();
     }

I've been told this is a bad design since type check means I have the wrong kind of abstraction and it violates the Liskov substitution principle. What would you do then? How would you fix this bad design?

Aucun commentaire:

Enregistrer un commentaire