Skip to main content
3 of 3
Copy edited (e.g. ref. <https://en.wiktionary.org/wiki/your#Determiner> and <https://en.wikipedia.org/wiki/Sentence_clause_structure#Run-on_sentences>). Brevity. Used a more direct cross reference (as user names can change at any time).

Like Dave points out in the comments, I believe your question is too abstract to be answered. I took the liberty turn it into a concrete (but still simplified) example.

class Pet {...} // accessors inside
class Cat extends Pet {...} // accessors inside
class Hamster extends Pet {...} // accessors inside

class PetFeeder {
    void feedPet(Pet pet) {
        if(pet instanceof Cat) {
            this.feedChicken(pet);
        }
        if(pet instanceof Hamster) {
            this.feedCarrots(pet);
        }
        throw;
    }
    void feedChicken(Pet) { ... }
    void feedCarrots(Pet) { ... }
}

So what is the problem with this code? It is tightly coupled; whenever you want to add a new type of pet you also have to adjust PetFeeder, even for tiny changes like changing the name of Cat to HouseCat. Instead, you want to have the model contain the differences that make you treat your Bar and Baz differently.

In our example this would be by adding a isCarnivore method to the Pet super class.

class Pet { abstract boolean isCarnivore(); }
class Cat extends Pet { boolean isCarnivore() { return true;} }
class Hamster extends Pet { boolean isCarnivor() { return false;} }

class PetFeeder {
    void feedPet(Pet pet) {
        if (pet.isCarnivore()) {
            this.feedChicken(pet);
        } else {
            this.feedCarrots(pet);
        }
    }
    void feedChicken(Pet) { ... }
    void feedCarrots(Pet) { ... }
}

If you would now add a new class Bunny, you can do it all in one place, let isCarnivore return true and be done with it.

In this design there is no automatic throw if a new class isn't known about. This is a feature and helps you to decouple business logic. But the drawback is that you wouldn't know if your new Pet is a carnivore, but only eats live mice.

If you need to be sure that your pets are not starving, you would want to keep the coupling of your previous design and look into the visitor pattern to get rid of the instanceof.

Helena
  • 827
  • 7
  • 11