Best Practices, Byte-sized

Ron’s Clean Architecture Tidbits: Single Responsibility

One of my favorite architecture 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):
<#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. 🚀



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store