Boss lesson · Unit 07
A bank
Accounts, transfers and a history that cannot be broken
What you practise
- Accounts, transfers and a history, rules enforced by methods and thrown errors
- A first design reviewed and improved
Try a question from this lesson
Pick one
A first design for a bank: an account is a plain object. Ada has 50 and takes out 80. What prints?
const acct = { name: "Ada", balance: 50 };
acct.balance -= 80;
console.log(acct.balance);Correct answer
-30
Why
Nothing stops it. A plain object cannot have rules: any line, anywhere in the program, can set any balance. For a bank, the account itself must be able to say no. That is a job for a class.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A better design
Make the balance private, and let methods be the only way in. Each method checks its rule first and throws when the rule is broken.
Reading stays easy, through a getter. Changing is only possible in the ways the class allows.
class Account {
#balance = 0;
constructor(owner) {
this.owner = owner;
}
get balance() {
return this.#balance;
}
deposit(n) {
if (n <= 0) {
throw new Error("bad amount");
}
this.#balance += n;
}
}Concept
Keep a history
A bank must be able to say how a balance came about. So every change also pushes a record onto a private list.
The getter hands out a copy of that list. Callers can read it, sort it and cut it up, and the real history stays as it was.
class Account {
#history = [];
deposit(n) {
this.#history.push("in " + n);
}
get history() {
return [...this.#history]; // a copy
}
}10 more exercises in the app
- 1× fill the blanks
- 3× type the answer
- 3× multiple choice
- 1× order the lines
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.