There was some chatter on twitter today about why SOLID principles are a good idea. When designing object systems we often tote around a lot of acronyms for principles of good design, but why are these things principles? It’s not enough to simply say “just because.” So right here and now I’d like to examine the “why” of some time tested OO aphorisms.
Yes, SOLID has been covered many times in many places, but it’s hard to find a single resource explaining the reasoning behind these ideas. Please spare me the “I wrote this post 18 months ago.” I won’t go into the “what” or “how” because I think that’s been covered inside and out. We’re here to talk about the principals behind the principals. Namely: what does SOLID buy you.
Now that all necessary disclaimers have been, well, disclaimed, here goes!
Single Responsibility Principle (SRP)
SRP simply states that a class should have one and only one reason to change. There is a clear reason for this: making sure your classes embody one purpose in life makes your system more receptive to change, more stable. Once you’ve nailed an object’s raison d’être chances are you can move on with your life. You don’t need to introduce changes that can, in turn, introduce instability. From Uncle Bob Martin:
If a class has more then one responsibility, then the responsibilities become coupled. Changes to one responsibility may impair or inhibit the class’ ability to meet the others. This kind of coupling leads to fragile designs that break in unexpected ways when
Changes can also ripple through the system as classes depending on our multi-responsibility class (which is more likely to change than a single responsibility class)
have clients in other programs. It’s worth considering your responsibilities and favoring more discrete classes with fewer methods.
SRP is really about analyzing cohesion. If you’re interested in going deeper, I recommend checking out this entry on cohesion to better understand the science behind SRP. Did you, for example, know their are different levels and forms of cohesion?
Next up: the Open-Closed Principle…