DaedTech

Stories about Software

By

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?

Duck

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.

O is for Open/Closed Principle

The Open/Closed Principle states that code entities should be open for extension, but closed for modification.  To put this more concretely, you should write a class that does what it needs to flawlessly and not assuming that people should come in and change it later.  It’s closed for modification, but it can be extended by, for instance, inheriting from it and overriding or extending certain behaviors.  An example of running afoul of the open closed principle would be to have a switch statement somewhere that you needed to go in and add to every time you wanted to add a menu option to your application.

A great example of this in real life is sitting in your pocket in the form of a smart phone.  All such phones have app stores and these app stores let you extend the base functionality of the phone.  Sure, it ships with the basics: camera operation, actual calls, text messages, etc.  But via the app store, you can extend the phone’s capabilities to allow you to manage your todo list, play inane video games, and even serve as a flashlight or wireless access point.

The mechanism that allows you to do this is purely one of extension, however.  It’s not as though Apple, Google, and Microsoft put the OS source code up on github and invite you to dive in and start building games and flashlight functionality.  Rather, they make the core phone functionality closed for modification and they open it to extension.

L is for Liskov Substition Principle

The Liskov Substition Principle (LSP) is the one here that is most unique to object oriented programming.  The LSP says, basically, that any child type of a parent type should be able to stand in for that parent without things blowing up.

In other words, if you have a class, Animal, with a MakeNoise() method, then any subclass of Animal should reasonably implement MakeNoise().  Cats should meow, dogs should bark, etc.  What you wouldn’t do is define a MuteMouse class that throws IDontActuallyMakeNoiseException.  This violates the LSP, and the argument would be that this class has no business inheriting from Animal.

To picture this, imagine cooking yourself a stew.  If you’re anything like me, you’d only put things in there that were edible because you would want to eat the stew without picking through each bite, asking yourself repeatedly, “is this edible?”

I is for Interface Segregation Principle

The Interface Segregation Principle (ISP) says that you should favor many, smaller, client-specific interfaces over one larger, more monolithic interface.  In short, you don’t want to force clients to depend on things they don’t actually need.  Imagine your code consuming some big, fat interface and having to re-compile/deploy with annoying frequency because some method you don’t even care about got a new signature.

To picture this in the real world, think of going down to your local corner restaurant and checking out the menu.  You’ll see all of the normal menu mainstays, and then something that’s just called “soup of the day.”  Why do they do this?  Because the soup changes a lot and there’s no sense re-printing the menus every day.  Clients that don’t care about the soup needn’t even be concerned, and clients that do use a different interface — asking the server.

D is for Dependency Inversion

The Dependency Inversion Principle (DIP) encourages you to write code that depends upon abstractions rather than upon concrete details.  You can recognize this in code you read by looking for a class or method that takes something generic like “Stream” and performs operations on it, as opposed to instantiating a specific Filestream or Stringstream or whatever.  This gives the code in question a lot more flexibility — you can swap in anything that conforms to the Stream abstraction and it will still work.

To visualize this in your day to day, go down to your local store and pay for something with a credit card.  The clerk doesn’t examine your card and get out the “Visa Machine” after seeing that your card is a Visa.  He just takes your card, whatever it is, and swipes it.  Both you and the clerk depend on the credit card abstraction without worrying about specifics.

And, That’s SOLID!

Hopefully these visualizations help you.  If you’re always keeping SOLID in the back of your mind while writing code, you’re going to make whoever maintains that code a lot happier.  And, if you have an easy way to picture and remember the principles, you’re a lot more likely to keep them in mind.

 

16 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Tom
Tom
7 years ago

Great post. This is possibly the easiest to understand example I’ve seen for Liskov Substition Principle, which I always struggle to articulate into a real life example.

Erik Dietrich
7 years ago
Reply to  Tom

Yeah, the LSP is pretty hard to articulate in an example. Glad to hear you found this one helpful!

Julian Hall
Julian Hall
7 years ago
Reply to  Tom

+1. It also makes clear why IReadOnlyList being a subtype of IList is a problem. Just using the typical description of LSP brings up objections that it doesn’t apply because the exceptional behaviour is documented in the supertype – it doesn’t matter though, because you still have to check if you don’t want your list modifying methods crashing…

Erik Dietrich
7 years ago
Reply to  Julian Hall

Definitely agreed. Sticking a flag in the supertype is almost worse because now you’re forcing poor man’s polymorphism on EVERY client of the supertype, and not just those that care about the particular subtype’s peculiarities. I think you get defenders of that, maybe, in the way that there’s always seemed to be the sentiment “if it’s a Microsoft framework/language thing, then it’s right by definition.” I’ve always found the Handler(object sender, EventArgs args) pattern to be extremely awkward because the first thing I have to do in every single handler is cast an object to whatever I know the argument… Read more »

RB
RB
7 years ago

Great article! Like the summary of all the different principles in an easy to grasp method. Does the Open/Close principle operate on a per class basis? In an evolving project it would be hard to state that a class needs to be closed to modifications but open to extension. Also, one thing I think many people fail to mention is that Open/Close principle is usually present at the level of a system/module itself. For instance it would make sense to say v1 of an Api is not modified once it is released. v2 of the Api could extend and expand… Read more »

Julian Hall
Julian Hall
7 years ago
Reply to  RB

OCP is the hardest to balance when you should use it versus not. Note that it is literally impossible for a system to fully comply in all aspects, and that following it usually involves increasing complexity. I personally think that it’s most important to comply when refactoring classes that are starting to accumulate multiple clients, particularly if you notice that you’re already making changes to it. This helps reducing coupling to frequently changing components, which is where most regressions come from.

Erik Dietrich
7 years ago
Reply to  RB

I think of the Open/Closed Principle as an aspirational, guiding principle and not a rule. Sure, it’d be great if every class you wrote was done as soon as you wrapped up at 5:00 and headed out, but the fact of the matter is that requirements evolve and plans change, so you often do need to modify classes or modules or whatever. For me, the biggest take-away is “don’t design things to need to be changed later.” It’s one thing if I design my class in such a way that I THINK it’s done, and it would be if not… Read more »

Geoffrey Payne
Geoffrey Payne
7 years ago

For Liskov, does this mean that every method in the parent class has to be virtual and overridden in the child class?

kmjungersen
kmjungersen
7 years ago
Reply to  Geoffrey Payne

I had the same question. Though after reading the wikipedia article on Liskov Substitution, I would assume you’re correct.

Great read though!

Erik Dietrich
7 years ago
Reply to  Geoffrey Payne

No, I don’t believe so. That would be a stronger guarantee. Liskov just says that if I have Base and Derived, I should be able to drop in a Derived anywhere I have a Base and the program will still behave correctly. Consider a degenerate example where I define “class Derived : Base { }” LSP is still preserved.

Noam
Noam
7 years ago

Great post. Love the examples.

Erik Dietrich
7 years ago
Reply to  Noam

Thanks!

Daniel Monteiro
Daniel Monteiro
7 years ago

Oddly enough, in Brazil, they often do get the “Visa” machine. Fortunately, this is getting old fast, with lots of payment startups picking up the slack from the giants and eating their lunch.

Erik Dietrich
7 years ago

Wow, really? I guess I was just superimposing my experience in the US and Europe on the world in general. I didn’t realize that there were places where there were actual Visa (or other specific brand) machines.

Martin Logan
Martin Logan
7 years ago

Great article. I was just thinking, LSP is not unique to only OO programming. It basically applies to protocols as well. Don’t remove elements or change semantics of existing elements, but add as you will for the obvious reasons.

Erik Dietrich
7 years ago
Reply to  Martin Logan

Thanks! And yeah, I think there’s wisdom in these principles that extends, situationally, beyond just OOP.