When building software systems we need to avoid a mess at any cost. The more messy software is, the more expensive is to change and maintain it.
Main design smells that lead to costs increase are:
- rigidity - when tight coupling leads to major rebuild and makes it harder to make changes
- fragility - when inappropriate and insufficient isolation of software parts leads to one change cause other unrelated modules crash or misbehave
- immobility - when software structures can not be reused
To avoid these design smells and make our software easy to change, understand and reuse we need a guide how to combine functions, data structures and classes - design principles.
That is where SOLID principles come into play.
1. The Single responsibility principle
The main idea of this principle is to separate classes and methods that each source file can have only one reason to change. The benefit of such separation is low coupling and low fragility.
2. The Open-Closed Principle
A software artifact should be open for extension but closed for modification For example, use of interfaces and dependency injection allows extending behavior without changing existing classes.
3. The Liskov Substitution Principle
Software systems should be built from substitutable (interchangeable) parts. If superclass does something, subclass should do it too (it should be substitutable for the superclass). Example of the violation of LSP will be when subtype does less than superclass. Then you need to add additional polluting behavior to your system.
4. The Interface Segregation Principle
Do not depend on things that you don’t use. Interface should have only methods that specific client use. Violation of this principle would be “Fat class”.
5. The Dependency Inversion Principle
The code that implements high-level policy should not depend on the code that implements low-level details.