Best Practices, Byte-sized

Ron’s Clean Code Tidbits: Single Responsibility

Ron Diamond (dev)
3 min readNov 21, 2022

One of my favorite clean coding tips is also one of the simplest. And possibly the most important.

A while back, I started adding a specific comment block to the top of new objects I create.

It’s simple. The template looks like this:

/**
Single Responsibility (SRP):
This
<#file/struct/class/enum#> implements …
*/

And after choosing the appropriate noun, I append a brief one- or two-sentence description of what the Single Responsibility (Principle) of that object is.

If it takes more than a sentence or two to describe what something does, that’s a code smell …

… as it easily might have more than one responsibility. In that case, I probably need to break it down into more than one object.

I found the technique so useful that I made the comment block into a code snippet:

… and with a keyboard completion shortcut, it pops right up in the code editor when I need it:

So here’s an example:

… and that’s a description of everything that file does. A good reminder, in case I’m tempted to add more than that.

Here’s another example …

… which encapsulates that object precisely.

And one more …

… and that perfectly describes its single purpose.

Written out this way, each object’s responsibility seems plainly obvious. And that’s the point. When it was unsaid, it may not have been as obvious; and so, it’d be easier to stray from it.

Though the real value in filling out that /* SRP comment block */ is that it forces me to think explicitly about an object’s single responsibility — and commit to some notion of that — before I even start writing its code.

This keeps me honest:
➢ It constrains the scope of what that object is for.
➢ It reminds me of what the responsibility is, as I’m filling in the code.
➢ Then, it tells others what its responsibility is.
➢ Not to mention me again, months later, when I’d long since have forgotten.

In addition, it reminds us all not to add in a bunch of unrelated stuff. Staying mindful of that too is just as important — now, and on into the future …

Oh, and there’s one other reason to like this practice:
➢ You’ve probably seen your share of inscrutable code. Wouldn’t it be nice to know, at a glance, what any given object is for?

So, a little snippet goes a long way.

Feel free to add the equivalent into your favorite IDE.

Your codebase (and your team) may thank you for it. 🚀

--

--

Ron Diamond (dev)
Ron Diamond (dev)

Written by Ron Diamond (dev)

Software craftsman, specializing in native mobile apps. rondiamond.net

No responses yet