Design Patterns – What Does ‘Encapsulate What Varies’ Mean?

designdesign-patternsencapsulationobject-oriented

One of the OOP principles I came across is: -Encapsulate what varies.

I understand what the literal meaning of the phrase is i.e. hide what varies. However, I don't know how exactly would it contribute to a better design. Can someone explain it using a good example?

Best Answer

You can write code that looks like this:

if (pet.type() == dog) {
  pet.bark();
} else if (pet.type() == cat) {
  pet.meow();
} else if (pet.type() == duck) {
  pet.quack()
}

or you can write code that looks like this:

pet.speak();

If what varies is encapsulated then you don't have to worry about it. You just worry about what you need and whatever you're using figures out how to do what you really need based on what varied.

Encapsulate what varies and you don't have to spread code around that cares about what varied. You just set pet to be a certain type that knows how to speak as that type and after that you can forget which type and just treat it like a pet. You don't have to ask which type.

You might think type is encapsulated because a getter is required to access it. I don't. Getter's don't really encapsulate. They just tattle when someone breaks your encapsulation. They're a nice decorator like aspect oriented hook that is most often used as debugging code. No matter how you slice it, you're still exposing type.

You might look at this example and think I'm conflating polymorphism and encapsulation. I'm not. I'm conflating "what varies" and "details".

The fact that your pet is a dog is a detail. One that might vary for you. One that might not. But certainly one that might vary from person to person. Unless we believe this software will only ever be used by dog lovers it's smart to treat dog as a detail and encapsulate it. That way some parts of the system are blissfully unaware of dog and wont be impacted when we merge with "parrots are us".

Decouple, separate, and hide details from the rest of the code. Don't let knowledge of details spread through your system and you'll be following "encapsulate what varies" just fine.

Related Topic