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.
  • Open-Closed - add functionality without changing the existing class. Design interface to use, say save, instead of saveAsFile and saveToDatabase. Then save couple be polymorphic based on what was needed, implementing that interface.
  • 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: