@@ -1022,38 +1022,84 @@ class UserSettings {
1022
1022
As stated by Bertrand Meyer, "software entities (classes, modules, functions,
1023
1023
etc.) should be open for extension, but closed for modification." What does that
1024
1024
mean though? This principle basically states that you should allow users to
1025
- extend the functionality of your module without having to open up the ` .js `
1026
- source code file and manually manipulate it.
1025
+ add new functionalities without changing existing code.
1027
1026
1028
1027
** Bad:**
1029
1028
``` javascript
1030
- class AjaxRequester {
1029
+ class AjaxAdapter extends Adapter {
1031
1030
constructor () {
1032
- // What if we wanted another HTTP Method, like DELETE? We would have to
1033
- // open this file up and modify this and put it in manually.
1034
- this .HTTP_METHODS = [' POST' , ' PUT' , ' GET' ];
1031
+ super ();
1032
+ this .name = ' ajaxAdapter' ;
1035
1033
}
1034
+ }
1036
1035
1037
- get (url ) {
1038
- // ...
1036
+ class NodeAdapter extends Adapter {
1037
+ constructor () {
1038
+ super ();
1039
+ this .name = ' nodeAdapter' ;
1040
+ }
1041
+ }
1042
+
1043
+ class HttpRequester {
1044
+ constructor (adapter ) {
1045
+ this .adapter = adapter;
1046
+ }
1047
+
1048
+ fetch (url ) {
1049
+ if (this .adapter .name === ' ajaxAdapter' ) {
1050
+ return makeAjaxCall (url).then (response => {
1051
+ // transform response and return
1052
+ });
1053
+ } else if (this .adapter .name === ' httpNodeAdapter' ) {
1054
+ return makeHttpCall (url).then (response => {
1055
+ // transform response and return
1056
+ });
1057
+ }
1039
1058
}
1059
+ }
1060
+
1061
+ function makeAjaxCall (url ) {
1062
+ // request and return promise
1063
+ }
1040
1064
1065
+ function makeHttpCall (url ) {
1066
+ // request and return promise
1041
1067
}
1042
1068
```
1043
1069
1044
1070
** Good** :
1045
1071
``` javascript
1046
- class AjaxRequester {
1072
+ class AjaxAdapter extends Adapter {
1047
1073
constructor () {
1048
- this .HTTP_METHODS = [' POST' , ' PUT' , ' GET' ];
1074
+ super ();
1075
+ this .name = ' ajaxAdapter' ;
1049
1076
}
1050
1077
1051
- get (url ) {
1052
- // ...
1078
+ request (url ) {
1079
+ // request and return promise
1080
+ }
1081
+ }
1082
+
1083
+ class NodeAdapter extends Adapter {
1084
+ constructor () {
1085
+ super ();
1086
+ this .name = ' nodeAdapter' ;
1053
1087
}
1054
1088
1055
- addHTTPMethod (method ) {
1056
- this .HTTP_METHODS .push (method);
1089
+ request (url ) {
1090
+ // request and return promise
1091
+ }
1092
+ }
1093
+
1094
+ class HttpRequester {
1095
+ constructor (adapter ) {
1096
+ this .adapter = adapter;
1097
+ }
1098
+
1099
+ fetch (url ) {
1100
+ return this .adapter .request (url).then (response => {
1101
+ // transform response and return
1102
+ });
1057
1103
}
1058
1104
}
1059
1105
```
0 commit comments