Today I Learned - Rocky Kev

TIL The Single Responsibility Principle

POSTED ON:

TAGS:

The Single Responsibility Principle via 97 Things:

Gather together those things that change for the same reason, and separate those things that change for different reasons.

This principle is often known as the Single Responsibility Principle or SRP. In short, it says that a subsystem, module, class, or even a function, should not have more than one reason to change.

To use a JS Example:

// this class defines the shape of the model. It represents the car.
class Car {
constructor(name, model, year) {
this.name = name
this.model = model
this.year = year
}
}

// this class gets/saves an object. It can be used to represent a instance of the car.
class CarService {
getCar(id) {
return this.http.get('api/cars/'+id)
}
saveCar(car) {
this.http.post('api/cars', car)
}
}

This example points to two classes. One might go, "Wait, they're both dealing with cars. Why not combine them?" Because then it violates the Single Responsibility Principle.

The Car is a model (the shape of how you want data to look like), while the CarService is about fetching api data.

It depends

This principle is pretty solid overall. But I'd also put it in a: 'it depends'.
Following this rule 95% of the time, you shouldn't have a problem.

I often see this principle being abused where every little feature is abstracted for the sake of 'DRY code'.
The key word is 'Responsibility', and that's where people get hung over.

A good rule of thumb is to "Abstract when you can strongly consider reasons".

For example, a Vue Component whose responsibility is to show a Google Map can simply be a single component. Inside that component may be a bunch of custom methods that adjust the style/design/output.

A developer may argue that the code is breaking the Single Responsibility Principle because it should be separating how you fetch the data, how you style the data, and how you output the data. In other words, shift what the 'Responsibility' is.

But from my position: "Can you identify where you want to reuse this code?"

So it depends!

References

Single Responsibility principle in 97 things

A easier to read version of it for JS devs from LogRocket


Related TILs

Tagged:

TIL the Singleton Pattern is hotly debated

Singleton Pattern is useful when exactly one object is needed to be used as a global instance to coordinate across the system. But it got problems.

TIL The Single Responsibility Principle

Gather together those things that change for the same reason, and separate those things that change for different reasons... if it makes sense.

TIL KISS (Keep it simple stupid)

I'm a fan of Keep it Stupidly Simple (KISS) (There's other ways to interpret the the last part).