Encapsulate what changes

By Karol Bocian | February 28, 2020

Encapsulate what may change

Hide changing code under abstraction.

Examples:

Tickets: We can hide condition like is the ticket valid in a separate method.

Animals: Animals (Cat, Dog) have a voice. We have a class AnimalConcert. It calls all animal voices.  In this method, AnimalsConcert iterate through all animals, check their type and give a voice for it.

We can add an interface IAnimal with method GetVoice. All animals can implement it. The implementation of giving voice is moved from AnimalsConcert to Dog and Cat. Now, AnimalsConcert iterates through all animals and call their method GetVoice. Now, when we add a new animal, we should only add a class with this new animal. We shouldn’t change AnimalConcert implementation.

Advantages

  • Less code to modify when making changes.
  • Clients depend on abstraction, not on low-level details (the Dependency Inversion Principle).
  • Easier maintenance.
  • Easier testing

Disadvantages

  • More abstractions.

All posts from mini project: Learn SOLID and OOP principles:

Sources

Main image

Materials

Leave a Reply

Your email address will not be published. Required fields are marked *