[S]OLID: The Single Responsibility Principle

Make life easier on yourself and people who need to read your code by asking your classes to do just one thing.

Posted on 07/12/2021 by Kasey Wahl
...

Dear Coder,

Designing software is hard.

This is true for a lot of reasons, but most of those reasons boil down to one cold reality:

Software is notoriously complex.

That's why, as an application becomes more complex, it becomes all the more important for a skilled programmer to follow some general rules to make their software leaner, more legible, and more modular.

Robert C. Martin's famous paper, Design Principles and Design Patterns covers a particular subset of design concepts known by the acronym, SOLID.

I'll cover each of the SOLID principles in full, but today, I'm just going to cover "S."

"S." stands for the Single Responsibility Principle.

Let's talk a bit about "responsibility" here, as it's meaning is a bit more specific in this instance than our normal colloquial understanding of the term.

According to Martin, "responsibility" in OOP simply means that a class should only ever have one reason to change.

Software that adheres to the single responsibility principle is generally easier to maintain, more testable, and extensible.

Why?

It might be easier to explain with an example.

Let's consider this class I've written for a blog post:


It's not very good. Why? Excusing the fact that it's likely too simple to really function (and that it only has an http "Get" method for the Create action), it's a class that is trying to do too many things. It's trying to define properties of what a blog post looks like, handle the creation and deletion of posts, and even implement a search feature.

In other words, it has three different responsibilities when it should only have one.

How can I fix this problem?

Consider MVC architecture, which by design adheres to the Single Responsibility Principle.

I can separate my bulky, cumbersome BlogPost class into three leaner classes that only do one thing each.

I create a BlogPost model, which solely cares about the "shape" of my data.



I create a Controller class, which handles database queries.



And finally, I create a basic search service class, which only handles returning matches to a user's search string.


This code is more clearly defined and organized, and much easier for another developer to maintain.

And that's all I'll say about the Single Responsibility Principle, Dear Coder.

As always, godspeed in your keystrokes.


Clickity Clacks,

Kasey


0 Comment(s)
Login to add a comment
Search
About Kasey
I love to make cool things with great people.

Let's grab a coffee and chat! (in person or on Zoom).

Connect with me on Github, LinkedIn, Twitter, or my personal website, kaseywahl.io.