In object-oriented programming, SOLID principles are key to making software designs more understandable, flexible, and maintainable. What are the SOLID principles you ask?
- Single Responsibility – A class should have only a single responsibility.
- Open Closed – Software entities should be open for extension, but closed for modification.
- Liskov Substitution – Clients should be able to consume any given implementation of an interface without violating the correctness of the system.
- Interface Segregation – Many client specific interfaces are better than one general purpose interface.
- Dependency Inversion – High level modules should not depend on low level modules, they should both depend on abstractions.
Now that we have those formal definitions out of the way, what SOLID is and how you apply, it may not be clear. You also might be asking, do I really need to know this? The answer is emphatically Yes! You may work in the same software code base for months, even years. Do you want that time to be pleasant or a constant frustration?
Keeping your software code SOLID will help make your work and that of your colleagues much simpler and more productive in the weeks, months, and years ahead. Just ask anyone who has had to maintain clunky, monolithic, spaghetti code!
Below is an example of a Repository class. This class has a problem, though; it has two responsibilities. It enforces Domain Rules and has persistence concerns.
Here is a revised version of the CustomerRepository class; it now has only one responsibility that of persistence.
Below I’ve added a RulesCustomerRepository class that handles the Domain Rules. Now each class has its own responsibility. (The RulesCustomerRepository class is an example of the Decorator pattern from the GOF Design Patterns book.) Not only that, but I can now write unit tests for the domain rules in isolation without being encumbered by the database.
Still not convinced of the benefits? Consider the size of the Customer Repository as the persistence logic becomes more complex, and more domain rules are added over time. You also cannot write effective unit tests on the Domain Rules with the persistence concerns in the way.
If you would like to learn more about SOLID, I highly recommend Mark Seemann’s excellent course on Encapsulation and SOLID available on Pluralsight.
Reflection: One might argue, the sample code violates the interface segregation principle. Should these principles be practiced with strict adherence? Perhaps the level of adherence varies with context? I’ll leave it to the reader to decide.
Disclaimer: The code sample should be considered a toy whose purpose is primarily pedagogical. I endeavor to make code samples just real enough to be interesting but not so complex that they overwhelm.
