SOLID Principles
SOILD is acronym for five object oriented design principles by Robert Martin aka Uncle Bob. These are principles promote good design practices and help developers write robust, flexible and maintainable code.
Each letter in SOILD represents one of the below principles.
- Single Responsibility Principle (SRP): A class should have only one responsibility.
public class FileHandler {
public String readFile(String filePath) {
// Code to read data from file
}
public void writeFile(String filePath, String data) {
// Code to write data to file
}
}
- Open / Close Principle (OCP): A class should be open for extension but closed for modification. A new functionality can be added to class either by inheritance, interface or polymorphism without altering the existing code.
- Liskov Substitution Principle (LSP) : A derived class or a sub class should be substitutable to its parent class or base class.
- Interface Segregation Principle (ISP): We need to create specific interfaces for separate functionalities rather than creating a single interface with all functionalities.
- Dependency Inversion Principle (DIP): High level modules should depend on abstraction not on low level modules. Also abstraction should not depend on details but details should depend on abstraction.
The Dependency Inversion Principle is one of the five SOLID principles of object-oriented design. It states:
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
This principle suggests that we should rely on abstractions (interfaces or abstract classes) rather than concrete implementations. The idea is to reduce the coupling between different modules of a system, making the system more modular and easier to maintain or extend.
Dependency Inversion vs. Dependency Injection
- Dependency Inversion is a design principle that suggests that our code should depend on abstractions rather than concrete implementations.
- Dependency Injection is a design pattern that helps achieve the Dependency Inversion Principle by injecting dependencies into a class rather than the class creating the dependencies itself.
How Dependency Inversion Can Be Achieved:
Observer Pattern: The observer pattern is a behavioral design pattern where an object (the subject) maintains a list of dependents (observers) and notifies them of state changes. This follows DIP because the subject depends on the abstraction of observers rather than concrete implementations.
Anonymous Functions, Lambdas, Method References: These can be used to inject behavior into classes without depending on concrete implementations, helping to decouple the components.
Comments
Post a Comment