Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9fd64e0

Browse files
committed
Use getters and setters
1 parent d038b41 commit 9fd64e0

File tree

1 file changed

+55
-3
lines changed

1 file changed

+55
-3
lines changed

README.md

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@ readable, reusable, and refactorable software in JavaScript. Enjoy!
77
## Table of Contents
88
1. [Variables](#variables)
99
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)
1314

1415
## **Variables**
1516
### Use meaningful and pronounceable variable names
@@ -655,6 +656,57 @@ function combine(val1, val2) {
655656
```
656657
**[⬆ back to top](#table-of-contents)**
657658

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)**
658710

659711

660712
## **Classes**

0 commit comments

Comments
 (0)