Examples of SOLID principles compared to bad design
SOLID Principles is an acronym of five principles.
- S - Single Responsibility Principle
- O - Open/Closed Principle
- L - Liskov’s Substitution Principle
- I - Interface Segregation Principle
- D -Dependency Inversion Principle
Every class should have responsibility over a single part of the functionality and that responsibility should be entirely encapsulated by this class.
Example. Class Car has the following information:
- Model name, year of issue which should be from 2010 to 2019
- You can print details about a car object
bad design | good design |
---|---|
Car class contains properties and a method |
A car itself cannot print. Create another class Printer with a method which takes Car object as a parameter |
OCP = Open / closed principle
Classes should be open for extension, but closed for modification.
Example. Class Reporting has the following information:
- You can create report about a car object in both pdf and docx formats
bad design | good design |
---|---|
Reporting class contains property and a method PrintData which cosists of multiply if-else. |
Make method PrintData virtual and create two derived classes to override this method |
Derived classes should extend base classes not change it.
Example:
Base class Vehicle contains two methods of calculating a rent of vehicle and getting information about it.
Classes Bus and Car inherit from Vehicle but there is no ability to rent a Bus.
Classes should not depend on methods they do not use.
Example. Two classes with similar functionaly Bus and Car:
- You can print details about a vehicle
- You can add new car but not a new bus.
High-level classes should not depend on low-level classes.
Example. Classes which can send notifications by e-mail.