SOLID class design principles
Learn about SOLID class design principles and the Single Responsibility Principle.
We'll cover the following
In the mid-1990s, Robert C. Martin gathered five principles for object-oriented class design, presenting them as the best guidelines for building a maintainable object-oriented system. Michael Feathers attached the acronym SOLID to these principles in the early 2000s.
- Single Responsibility Principle (SRP): Classes should have one reason to change. Keep classes small and single-purposed.
- Open-Closed Principle (OCP): Design classes are to be open for extension but closed for modification. Minimize the need to make changes to existing classes.
- Liskov Substitution Principle (LSP): Subtypes should be substitutable for their base types. From a client’s perspective, override methods shouldn’t break functionality.
- Interface Segregation Principle (ISP):
Clients should not be forced to depend on methods they don’t use. Split a larger interface into a number of smaller interfaces. - Dependency Inversion Principle (DIP): 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.
Single Responsibility Principle (SRP)
We will take a look at some bigger design concerns. Specifically, we’ll focus on the Single Responsibility Principle (SRP), which guides us to small classes that increase flexibility and ease of testing.
The principle states that every module, class, or function in a computer program should have responsibility for a single part of that program’s functionality
Benefits of SRP
- The focus of a class on a single responsibility decreases the risk of change.
- The more responsibilities a class has, the easier it is to break other existing behavior when changing code within the class.
- Smaller, more focused classes are also more likely to provide a lot of reuse value. In contrast, a very large class with lots of responsibilities cannot possibly be used in other contexts.
Get hands-on with 1400+ tech skills courses.