Skip to content

Commit dfe15ca

Browse files
committed
SRP
1 parent 9fd64e0 commit dfe15ca

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,6 +710,63 @@ bankAccount.withdraw(100);
710710

711711

712712
## **Classes**
713+
### Classes should obey Single Responsibility Principle (SRP)
714+
As stated in Clean Code, "There should never be more than one reason for a class
715+
to change". It's tempting to jam-pack a class with a lot of functionality, like
716+
when you can only take one suitcase on your flight. The issue with this is
717+
that your class won't be conceptually cohesive and it will give it many reasons
718+
to change. Minimizing the amount of times you need to change a class is important.
719+
It's important because if too much functioanlity is in one class and you modify a piece of it,
720+
it can be difficult to understand how that will affect other dependent modules in
721+
your codebase.
722+
723+
**Bad:**
724+
```javascript
725+
class UserSettings {
726+
constructor(user) {
727+
this.user = user;
728+
}
729+
730+
changeSettings(settings) {
731+
if (this.verifyCredentials(user)) {
732+
// ...
733+
}
734+
}
735+
736+
verifyCredentials(user) {
737+
// ...
738+
}
739+
}
740+
```
741+
742+
**Good**:
743+
```javascript
744+
class UserAuth {
745+
constructor(user) {
746+
this.user = user;
747+
}
748+
749+
verifyCredentials() {
750+
// ...
751+
}
752+
}
753+
754+
755+
class UserSettings {
756+
constructor(user) {
757+
this.user = user;
758+
this.auth = new UserAuth(user)
759+
}
760+
761+
changeSettings(settings) {
762+
if (this.auth.verifyCredentials()) {
763+
// ...
764+
}
765+
}
766+
}
767+
```
768+
**[⬆ back to top](#table-of-contents)**
769+
713770
### Prefer ES6 classes over ES5 plain functions
714771
It's very difficult to get readable class inheritance, construction, and method
715772
definitions for classical ES5 classes. If you need inheritance (and be aware

0 commit comments

Comments
 (0)