Skip to content

Commit b19273f

Browse files
committed
Open/Closed Principle
1 parent 59def82 commit b19273f

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

README.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -763,7 +763,7 @@ console.log('Employee name: ' + employee.getName()); // Employee name: John Doe
763763

764764

765765
## **Classes**
766-
### Classes should obey Single Responsibility Principle (SRP)
766+
### Single Responsibility Principle (SRP)
767767
As stated in Clean Code, "There should never be more than one reason for a class
768768
to change". It's tempting to jam-pack a class with a lot of functionality, like
769769
when you can only take one suitcase on your flight. The issue with this is
@@ -820,6 +820,47 @@ class UserSettings {
820820
```
821821
**[⬆ back to top](#table-of-contents)**
822822

823+
### Open/Closed Principle (OCP)
824+
As stated by Bertrand Meyer, "software entities (classes, modules, functions,
825+
etc.) should be open for extension, but closed for modification." What does that
826+
mean though? This principle basically states that you should allow users to
827+
extend the functionality of your module without having to open up the `.js`
828+
source code file and manually manipulate it.
829+
830+
**Bad:**
831+
```javascript
832+
class AjaxRequester {
833+
constructor() {
834+
// What if we wanted another HTTP Method, like DELETE? We would have to
835+
// open this file up and modify this and put it in manually.
836+
this.HTTP_METHODS = ['POST', 'PUT', 'GET'];
837+
}
838+
839+
get(url) {
840+
// ...
841+
}
842+
843+
}
844+
```
845+
846+
**Good**:
847+
```javascript
848+
class AjaxRequester {
849+
constructor() {
850+
this.HTTP_METHODS = ['POST', 'PUT', 'GET'];
851+
}
852+
853+
get(url) {
854+
// ...
855+
}
856+
857+
addHTTPMethod(method) {
858+
this.HTTP_METHODS.push(method);
859+
}
860+
}
861+
```
862+
**[⬆ back to top](#table-of-contents)**
863+
823864
### Prefer ES6 classes over ES5 plain functions
824865
It's very difficult to get readable class inheritance, construction, and method
825866
definitions for classical ES5 classes. If you need inheritance (and be aware

0 commit comments

Comments
 (0)