@@ -7,9 +7,10 @@ readable, reusable, and refactorable software in JavaScript. Enjoy!
7
7
## Table of Contents
8
8
1 . [ Variables] ( #variables )
9
9
2 . [ Functions] ( #functions )
10
- 3 . [ Classes] ( #classes )
11
- 4 . [ Concurrency] ( #concurrency )
12
- 5 . [ Comments] ( #comments )
10
+ 3 . [ Objects and Data Structures] ( #objects-and-data-structures )
11
+ 4 . [ Classes] ( #classes )
12
+ 5 . [ Concurrency] ( #concurrency )
13
+ 6 . [ Comments] ( #comments )
13
14
14
15
## ** Variables**
15
16
### Use meaningful and pronounceable variable names
@@ -655,6 +656,57 @@ function combine(val1, val2) {
655
656
```
656
657
** [ ⬆ back to top] ( #table-of-contents ) **
657
658
659
+ ## ** Objects and Data Structures**
660
+ ### Use getters and setters
661
+ JavaScript doesn't have interfaces or types so it is very hard to enforce this
662
+ pattern, because we don't have keywords like ` public ` and ` private ` . As it is,
663
+ using getters and setters to access data on objects if far better than simply
664
+ looking for a property on an object. "Why?" you might ask. Well, here's an
665
+ unorganized list of reasons why:
666
+
667
+ 1 . When you want to do more beyond getting an object property, you don't have
668
+ to look up and change every accessor in your codebase.
669
+ 2 . Makes adding validation simple when doing a ` set ` .
670
+ 3 . Encapsulates the internal representation.
671
+ 4 . Easy to add logging and error handling when getting and setting.
672
+ 5 . Inheriting this class, you can override default functionality.
673
+ 6 . You can lazy load your object's properties, let's say getting it from a
674
+ server.
675
+
676
+
677
+ ** Bad:**
678
+ ``` javascript
679
+ class BankAccount {
680
+ constructor () {
681
+ this .balance = 1000 ;
682
+ }
683
+ }
684
+
685
+ let bankAccount = new BankAccount ();
686
+ // Buy shoes...
687
+ bankAccount .balance = bankAccount .balance - 100 ;
688
+ ```
689
+
690
+ ** Good** :
691
+ ``` javascript
692
+ class BankAccount {
693
+ constructor () {
694
+ this .balance = 1000 ;
695
+ }
696
+
697
+ // It doesn't have to be prefixed with `get` or `set` to be a getter/setter
698
+ withdraw (amount ) {
699
+ if (verifyAmountCanBeDeducted (amount)) {
700
+ this .balance -= amount;
701
+ }
702
+ }
703
+ }
704
+
705
+ let bankAccount = new BankAccount ();
706
+ // Buy shoes...
707
+ bankAccount .withdraw (100 );
708
+ ```
709
+ ** [ ⬆ back to top] ( #table-of-contents ) **
658
710
659
711
660
712
## ** Classes**
0 commit comments