SRP — The Single Responsibility Principle
SRP is a part of SOLID, a mnemonic acronym which bundles a total of 5 design principles.
But what is SRP, is it important, and should you care?
What does it state?
I could give you my own definition now, but Robert C. Martin has already given a pretty great one when he first wrote about this principle:
“A class should have one, and only one reason to change”
Although he specifically stated classes, we can also apply the principle to modules and functions. So, when you have a class, a module, or a function, there should be exactly one reason to change code within it.
Not two, not three, only one.
A basic example
Let’s take a look at a pretty basic example, a function that creates some report data. And as you will see, there is an issue within this function. It does more than one thing.
function createReportData(user) {
const lowerCasedForename = user.forename.toLowerCase();
const capitalizedForename = lowerCasedForename.charAt(0).toUpperCase() + lowerCasedForename.slice(1);
const greeting = `Hello ${capitalizedForename}!`;
return {
id: user.id,
name: user.name,
forename: user.forename,
greeting
};
}