SOLID: Single Responsibility Principle in JavaScript

Carsten Behrens
2 min readJan 17, 2020

Photo by Thomas Tastet on Unsplash

A class should have one, and only one, reason to change

Robert C. Martin

The word ”class” here can also be replaced by ”module”, the point is that the Single Responsibility Principle (SRP) is not limited to object-oriented design.

The best way to understand the SRP is to look at some examples of code that violates this rule.

This class violates the SRP because it has more that one reason to change.

Let’s say that we wanted to change the reportHours method.

To do this we have to change the code inside the Employee class, which means that we could potentially break some of the other methods in our class.

If you think about it, it makes no sense.

Why should we be able to break something that does not need to change?

This is where the SRP is important, it ensures that there is only one reason to change. Robert C. Martin defines only one reason to change as ”should only be responsible to one”. In this case, this means that the Employee class should be split up into smaller classes.

This does not mean that the Employee class should only have one method, it can have many methods but it should only have one reason to change.

In Part two of this series of blog posts, we will take a look at the Interface Segregation Principle.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Carsten Behrens
Carsten Behrens

No responses yet

Write a response