The SOLID Principles
SOLID is an acronym for five other class-design principles:
The Single Responsibility Principle (SRP)
☑️ Topic: Objects and Data Structures
☑️ Idea: Each class should have a single responsibility. That means that there should be only one reason to change it. This is one of the SOLID principles.
☑️ Benefits: Maintainability, Reusability
☑️ Guideline: If you can’t say what the class does without using “and”, “or” , or “if” it’s likely doing more than one thing.
Benefits Explained
- Maintainability: A small class is easy to maintain. Having a single responsibility per class results in small classes.
- Classes are easier to understand: The smaller the class the fastest one can go through it and understand it.
- Naming classes: Naming is hard, right? Well if you only have one responsibility you can represent it in the class name. Having more than one responsibility makes it much harder to find a name that represents everything.
Example
BAD
// BAD class UserSettings { constructor(user) { this.user = user; } changeSettings(settings) { if (this.verifyCredentials()) { // ... } } verifyCredentials() { // ... } }
GOOD
// GOOD class UserAuth { constructor(user) { this.user = user; } verifyCredentials() { // ... } } class UserSettings { constructor(user) { this.user = user; this.auth = new UserAuth(user); } changeSettings(settings) { if (this.auth.verifyCredentials()) { // ... } } }