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:
- SOLID
- SOLID exercises
- S like Single responsibility principle
- SOLID exercises — Kata
- O as Open-closed principle
- L jak Liskov Substitution Principle
- Interface segregation principle
- KISS — Keep it simple, stupid
- DRY — Don’t repeat yourself
- Dependency inversion principle
- SLAP — Single Level of Abstraction Principle
- Composition Over Inheritance
- Encapsulate what changes
- Lod — Law of Demeter
- ES as Exercises of Single responsibility principle
- EO as Exercises of Open/closed principle
- EL as Exercises of Liskov Substitution Principle
- EI as Eexrcises of Interface segregation principle
- ES as Exercises of Dependency Inversion Principle
- Object-oriented programming
- OOP — Object-Oriented Programming — Advice
- OOP — Object Oriented Programming
Sources
Main image
Materials
- https://devcave.pl/notatnik-juniora/zasady-projektowania-kodu
- https://medium.com/@iamprabal/encapsulation-4f5392d172a3
- https://pl.cs.jhu.edu/oose/lectures/design-principles.shtml
Sorry, there was a YouTube error.