vendredi 30 décembre 2016

How to get rid of instanceof check when using inheritance?

Assume we have a class Animal, with subclasses as cat, eagle

Now I have a method:

public void process(Animal animal) {

   if (animal instanceof Cat) {
     if (!animal.meow()) {
        throw exception("cat does not meow");
     } else {
      animal.feedFish();
     }
   }

   if (animal instanceof eagle) {
      if (!animal.fly()) {
         throw exception("eagle does not fly");
      } else {
        animal.checkMaxFlightAltitude();
      }
   }
}

Here cat has 2 methods meow and feedfish which are completely different than eagle's methods fly and checkmaxflight

Most design patterns revolve around assumptions that subclasses have a common method like Shape draw() inherited by circle draw and square draw

  1. Is there some way to do validations on subclasses, such as cat and eagle without instanceof check ?

  2. Any good design pattern ( assuming subclasses dont share a method in base class ? )

Aucun commentaire:

Enregistrer un commentaire