SOLID Progamming Principles

May 18, 2024 note-to-self

The Principles:

  • Single Responsibility - the class should do one thing and thus would only have one stakeholder with a reason to change it. A class that handles a report. Two things can change: the content of the report and the format of the report. Those should be separate so if one changes, the other stays the same. Each has a single responsibility.
  • Open-Closed - add functionality without changing the existing class. Design interface to use, say save, instead of saveAsFile and saveToDatabase. Then save could be polymorphic based on what was needed, implementing that interface. Decorator pattern is a good example of altering or adding functionality without changing the existing class.
  • Liskov Substitution - a child class should not modify the parent/base class functionality, but only extend it. So, if you replaced the child/sub class with the parent/base class it should still work (the child class should have more, not less functionality). Bug due to this issue can be challenging to detect.
  • Interface Segregation - create specific interfaces, and extend them to create broader interfaces, so that you can mix and match them specifically.
  • Dependency Inversion - concrete implementations depend on interfaces and abstract classes, not concrete implementations. Type declarations would declare the type-hint for the interface instead of the concrete class. See the 2nd example link.

Examples and details:

  1. https://www.freecodecamp.org/news/solid-principles-explained-in-plain-english/
  2. https://phpisset.com/solid-in-php-the-dependency-inversion-principle
These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.