@@ -937,9 +937,7 @@ inventoryTracker('apples', req, 'www.inventory-awesome.io');
937937
938938## ** Objects and Data Structures**
939939### Use getters and setters
940- JavaScript doesn't have interfaces or types so it is very hard to enforce this
941- pattern, because we don't have keywords like ` public ` and ` private ` . As it is,
942- using getters and setters to access data on objects is far better than simply
940+ Using getters and setters to access data on objects could be better than simply
943941looking for a property on an object. "Why?" you might ask. Well, here's an
944942unorganized list of reasons why:
945943
@@ -948,56 +946,54 @@ to look up and change every accessor in your codebase.
948946* Makes adding validation simple when doing a ` set ` .
949947* Encapsulates the internal representation.
950948* Easy to add logging and error handling when getting and setting.
951- * Inheriting this class, you can override default functionality.
952949* You can lazy load your object's properties, let's say getting it from a
953950server.
954951
955952
956953** Bad:**
957954``` javascript
958- class BankAccount {
959- constructor () {
960- this .balance = 1000 ;
961- }
962- }
955+ function makeBankAccount () {
956+ // ...
963957
964- const bankAccount = new BankAccount ();
958+ return {
959+ balance: 0 ,
960+ // ...
961+ };
962+ }
965963
966- // Buy shoes...
967- bankAccount .balance - = 100 ;
964+ const account = makeBankAccount ();
965+ account .balance = 100 ;
968966```
969967
970968** Good:**
971969``` javascript
972- class BankAccount {
973- constructor (balance = 1000 ) {
974- this ._balance = balance;
970+ function makeBankAccount () {
971+ let balance = 0 ;
972+ // ...
973+
974+ function isValid (amount ) {
975+ // ...
975976 }
976977
977- // It doesn't have to be prefixed with `get` or `set` to be a getter/setter
978- set balance (amount ) {
979- if (this .verifyIfAmountCanBeSetted (amount)) {
980- this ._balance = amount;
981- }
978+ function getBalance () {
979+ return balance;
982980 }
983981
984- get balance () {
985- return this ._balance ;
982+ function setBalance () {
983+ if (isValid (amount)) {
984+ balance = amount;
985+ }
986986 }
987987
988- verifyIfAmountCanBeSetted ( val ) {
988+ return {
989989 // ...
990- }
990+ getBalance,
991+ setBalance
992+ };
991993}
992994
993- const bankAccount = new BankAccount ();
994-
995- // Buy shoes...
996- bankAccount .balance -= shoesPrice;
997-
998- // Get balance
999- let balance = bankAccount .balance ;
1000-
995+ const account = makeBankAccount ();
996+ account .setBalance (100 );
1001997```
1002998** [ ⬆ back to top] ( #table-of-contents ) **
1003999
0 commit comments