@@ -733,6 +733,90 @@ class Human extends Mammal {
733
733
```
734
734
** [ ⬆ back to top] ( #table-of-contents ) **
735
735
736
+
737
+ ### Use method chaining
738
+ Against the advice of Clean Code, this is one place where we will have to differ.
739
+ It has been argued that method chaining is unclean and violates the (Law of Demeter)
740
+ [ https://en.wikipedia.org/wiki/Law_of_Demeter ] . Maybe it's true, but this pattern
741
+ is very useful in JavaScript and you see it in many libraries such as jQuery and
742
+ Lodash. It allows your code to be expressive, and less verbose. For that reason,
743
+ I say, use method chaining and take a look at how clean your code will be.
744
+ In your class functions, simply return ` this ` at the end of every function, and
745
+ you can chain further class methods onto it.
746
+
747
+ ** Bad:**
748
+ ``` javascript
749
+ class Car {
750
+ constructor () {
751
+ this .make = ' Honda' ;
752
+ this .model = ' Accord' ;
753
+ this .color = ' white' ;
754
+ }
755
+
756
+ setMake (make ) {
757
+ this .name = name;
758
+ }
759
+
760
+ setModel (model ) {
761
+ this .model = model;
762
+ }
763
+
764
+ setColor (color ) {
765
+ this .color = color;
766
+ }
767
+
768
+ save () {
769
+ console .log (this .make , this .model , this .color );
770
+ }
771
+ }
772
+
773
+ let car = new Car ();
774
+ car .setColor (' pink' );
775
+ car .setMake (' Ford' );
776
+ car .setModel (' F-150' )
777
+ car .save ();
778
+ ```
779
+
780
+ ** Good** :
781
+ ``` javascript
782
+ class Car {
783
+ constructor () {
784
+ this .make = ' Honda' ;
785
+ this .model = ' Accord' ;
786
+ this .color = ' white' ;
787
+ }
788
+
789
+ setMake (make ) {
790
+ this .name = name;
791
+ // NOTE: Returning this for chaining
792
+ return this ;
793
+ }
794
+
795
+ setModel (model ) {
796
+ this .model = model;
797
+ // NOTE: Returning this for chaining
798
+ return this ;
799
+ }
800
+
801
+ setColor (color ) {
802
+ this .color = color;
803
+ // NOTE: Returning this for chaining
804
+ return this ;
805
+ }
806
+
807
+ save () {
808
+ console .log (this .make , this .model , this .color );
809
+ }
810
+ }
811
+
812
+ let car = new Car ()
813
+ .setColor (' pink' )
814
+ .setMake (' Ford' )
815
+ .setModel (' F-150' )
816
+ .save ();
817
+ ```
818
+ ** [ ⬆ back to top] ( #table-of-contents ) **
819
+
736
820
## ** Concurrency**
737
821
### Use Promises, not callbacks
738
822
Callbacks aren't clean, and they cause excessive amounts of nesting. With ES6,
0 commit comments