The SOLID Principles in Real Life
Editorial note: I originally wrote this post for the Infragistics blog. You can check out the original post here, at their site. There’s a lot of good content over there in general, so go check it out.
Hopefully you’re familiar with the SOLID principles, particularly if you program in object oriented languages. The wisdom contained therein (mostly) isn’t limited to object oriented languages, but such languages were the intended target.
If you’re not familiar and don’t have time to read the linked Wikipedia page, SOLID is a mnemonic acronym for five principles of object oriented programming or, as I hinted, really just programming in general (except, perhaps for the Liskov Substitution Principle). These concepts have been around since at least the early 2000s and have truly stood the test of time.
What you get by following them is code that’s a lot more likely to be maintainable. These design guidelines, properly followed, will tend to steer you toward writing clean code.
What I’d like to do is offer real life analogs of the principles. I’d imagine that this may make them easier to remember, but I think it can also serve to drive the points home in the first place and help encourage the “aha” moment if you haven’t yet had them. And, even if you have, it never hurts to have a visual to help reinforce the concept or to explain it someone else — even someone non-technical, potentially.
S is for Single Responsibility Principle
The single responsibility principle (SRP) asserts that a class or module should do one thing only. Now, this is kind of subjective, so the principle is reinforced with the heuristic that the class or module should have only one reason to change.
By way of counter-example, consider a class that opens a connection to the database, pulls out some table data, and writes the data to a file. This class has multiple reasons to change: adoption of a new database, modified file output format, deciding to use an ORM, etc. In terms of the SRP, we’d say that this class is doing too much.
In your day to day life, picture those “duck” vehicles you see occasionally in some lakeside towns. They’re street legal and water-capable, so a duck tour affords you the unique and surreal experience of being in a ‘car’ that gets to the edge of the water and just keeps going. Fun, right?
And yet, you don’t see a whole lot of them. There are millions of families out there that own both cars and boats, and there are very few families that buy these ducks. Do you know why? It’s most likely because no one wants to be unable to drive to work because their boat rudder is broken. Ducks are fun, but they’re also a great example of the pitfalls that the SRP can help you avoid.