Single Responsibility Principle

Published on Tuesday, January 02, 2024

The Single Responsibility Principle

I am a strong proponent of the SRP. It's the first element of SOLID, on which more shall surely come.

What is the SRP?

Wikipedia says that the SRP...

states that "A module should be responsible to one, and only one, actor."

...which I find inadequately explanatory (a.k.a. clear as mud).

How about...

the concept that any single object in object-oriented programing (OOP) should be made for one specific function

Nope. How is it limited to OOP?

Frequently, the SRP is characterized as "one software component should do just one thing", and that's true as far as it goes, but the reverse is also true, in that the "one thing" should only appear in the "one software component", otherwise known as DRY (Don't Repeat Yourself).

Why should you care?

Suppose you want to validate some user input, say, a password. This comes up all the time; some might say, too many times. You would want to have access to it in the UI, for immediate feedback to the user, and in the API, because you can't trust external input. If that validation is implemented in two different blocks of code, you have now created the possibility for them to be different, to disagree, and then frustrate your user when the UI says their password is fine, but it's rejected when they submit.

I've seen validation also appear as attributes on entity objects, such as required and minimum or maximum field length. Validation is not a database concern, it's a business rule. Attributes on entity objects should address database concerns, like foreign keys.

Don't make the developer look all over the codebase for where validation is happening!