If you’ve been around the coding block a few times, you have undoubtedly run across the term SOLID, an acronym for the class design focused first five principles of object oriented design by Uncle Bob.
If you haven’t heard about SOLID before, don’t worry - it’s friendly, and its here to help guide you away from nasty code pitfalls.
Before we get to the breakdown, here’s my own, humble opinion: SOLID is largely concerned with mitigating the inevitable negative effects of change. Change is constant, but that doesn’t mean we have our work blown away every time change huffs and puffs in our direction. If we write our code smartly, our code can be a tough, modular brick house rather than a fragile straw hut that will blow down with every change that comes our way.
This will be the first of five posts and serves as a simple introduction. Subsequent posts will dive into each of the letters of SOLID.
Single Responsibility
A class should have one, and only one, reason to change
If you have a class that does too many things, it will have many reasons to change in the future.
Open Closed Principle
A class should be open for extension, but closed for modification
Uncle Bob added:
This principle is the foundation for building code that is maintainable and reusable.
-Robert C. Martins
In other words, you shouldn’t have to modify the internals to add some functionality.
Liskov Substitution Principle
This one has a tricky, formal definition, so I’ll just use good ol’ Uncle Bob’s definition for now to ease into this principle.
Subtypes must be substitutable for their base types
This principle is concerned with classification - and therefore inheritance - and classification is tricky. Is a donut bread? Is it a cake? Is a hotdog a sandwich? I could substitute a donut for a slice of bread, and I could substitute a hotdog for a sandwich, and in both these cases, I might want to, so I’m going with yes for these.
I could not subsitute a tire from my car with my wedding ring, so these are things that should not be related at a class level, even though they’re both circles. The Liskov Substitution Principle asks you to think about classification in terms of behaviors - a donut can behave as bread, or as a cake. A hotdog can behave as a sandwich. I cannot use a tire as a wedding ring if one of the necessary behaviors is that it must fit well and be something I can wear every day.
Interface Segregation Principle
No client should be forced to depend on methods it does not use
In other words, don’t try to jam too many things into one interface, especially when they’re unrelated.
Dependency Inversion Principle
Classes should depend upon abstractions, not on concrete details.
If you want to turn off the lights, you shouldn’t have to pull the wiring out of the walls and change it.