@@ -893,6 +893,73 @@ let car = new Car()
893893```
894894** [ ⬆ back to top] ( #table-of-contents ) **
895895
896+ ### Prefer composition over inheritance
897+ As stated famously in the [ Gang of Four] ( https://en.wikipedia.org/wiki/Design_Patterns ) ,
898+ you should prefer composition over inheritance where you can. There are lots of
899+ good reasons to use inheritance and lots of good reasons to use composition.
900+ The main point for this maxim is that if your mind instinctively goes for
901+ inheritance, try to think if composition could model your problem better. In some
902+ cases it can. Inheritance is great for preventing
903+
904+ You might be wondering then, "when should I use inheritance?" It
905+ depends on your problem at hand, but this is a decent list of when inheritance
906+ makes more sense than composition:
907+
908+ 1 . Your inheritance represents an "is-a" relationship and not a "has-a"
909+ relationship (Animal->Human vs. User->UserDetails).
910+ 2 . You can reuse code from the base classes (Humans can move like all animals).
911+ 3 . You want to make global changes to derived classes by changing a base class.
912+ (Change the caloric expenditure of all animals when they move).
913+
914+ ** Bad:**
915+ ``` javascript
916+ class Employee {
917+ constructor (name , email ) {
918+ this .name = name;
919+ this .email = email;
920+ }
921+
922+ // ...
923+ }
924+
925+ // Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee
926+ class EmployeeTaxData extends Employee {
927+ constructor (ssn , salary ) {
928+ super ();
929+ this .ssn = ssn;
930+ this .salary = salary;
931+ }
932+
933+ // ...
934+ }
935+ ```
936+
937+ ** Good** :
938+ ``` javascript
939+ class Employee {
940+ constructor (name , email ) {
941+ this .name = name;
942+ this .email = email;
943+
944+ }
945+
946+ setTaxData (ssn , salary ) {
947+ this .taxData = new EmployeeTaxData (ssn, salary);
948+ }
949+ // ...
950+ }
951+
952+ class EmployeeTaxData {
953+ constructor (ssn , salary ) {
954+ this .ssn = ssn;
955+ this .salary = salary;
956+ }
957+
958+ // ...
959+ }
960+ ```
961+ ** [ ⬆ back to top] ( #table-of-contents ) **
962+
896963## ** Concurrency**
897964### Use Promises, not callbacks
898965Callbacks aren't clean, and they cause excessive amounts of nesting. With ES6,
0 commit comments