Problem overview
The lesson asks for a BankAccount class that keeps its balance private. Other code can't touch the number directly. It can only call methods, and those methods enforce the rules of the account. This is encapsulation: an object owns its data and decides how that data may change.
The class has four members:
constructor(initialBalance: number)starts the account with the given balance.deposit(amount: number): voidadds to the balance, but ignores an amount that is zero or negative.withdraw(amount: number): booleansubtracts from the balance and returnstrue, unless the amount is zero or negative or larger than the balance. Then it changes nothing and returnsfalse. Withdrawing exactly the whole balance is allowed.getBalance(): numberis the only way to read the balance from outside.
The driver starts an account with 100, deposits 50, withdraws 30 and then tries to withdraw 200. It prints the balance, tries three invalid operations, withdraws the remaining 120, and tries to withdraw 1 more. The expected output is Balance: 120, Balance: 120, Withdrew all, Balance: 0 and Rejected.
Approach: a private field and methods that guard it
The balance lives in a field named #balance. The # prefix makes it a JavaScript private field: only code written inside the class body can use it, as this.#balance. Every change to the balance goes through deposit or withdraw, so the rules are written once and can't be bypassed.
Both methods follow the same pattern: guard first, change second. A guard is an if at the top of the method that leaves immediately when the request is invalid. Past the guard the code can assume the amount is acceptable and update the balance without further checks. deposit leaves silently, because it returns void. withdraw returns false to tell the caller the money didn't move, and true at the end when it did.
Tracing the driver
Running the lesson's calls one at a time, with the balance after each:
| Call | Returns | Balance after |
|---|---|---|
deposit(50) | nothing | 150 |
withdraw(30) | true | 120 |
withdraw(200) | false | 120 |
deposit(-20) | nothing | 120 |
deposit(0) | nothing | 120 |
withdraw(-5) | false | 120 |
withdraw(120) | true | 0 |
withdraw(1) | false | 0 |
Step by step
- Declare the class
BankAccountand write its closing brace at once. Everything below goes inside it. - Declare the private field
#balance: number;. The declaration is required: a#field must be declared in the class body beforethis.#balancecan be used. - Start the constructor with one parameter,
initialBalance: number. - Store the starting balance in
this.#balance, so a new account begins with the amount it is given. - Start
deposit, with anumberparameter namedamountand the return typevoid. - Add the deposit guard: a one-line
ifthat returns whenamountis zero or less. - Add the amount to
this.#balance. Only positive amounts get past the guard. - Start
withdraw, takingamountand returning aboolean. - Add the withdrawal guard with two conditions joined by
||: the amount isn't positive, or it is more than the balance. In either case returnfalse. The comparison is>, not>=, so asking for exactly the whole balance is allowed. - Subtract the amount from
this.#balance. - Return
true, because reaching this line means the money left the account. - Start
getBalance, with no parameters and the return typenumber. - Return
this.#balance. The caller gets a copy of the number, so reading it can't change the account.
The solution in TypeScript
class BankAccount {
#balance: number;
constructor(initialBalance: number) {
this.#balance = initialBalance;
}
deposit(amount: number): void {
if (amount <= 0) return;
this.#balance += amount;
}
withdraw(amount: number): boolean {
if (amount <= 0 || amount > this.#balance) return false;
this.#balance -= amount;
return true;
}
getBalance(): number {
return this.#balance;
}
}
const account = new BankAccount(100);
account.deposit(50);
account.withdraw(30);
account.withdraw(200);
console.log("Balance: " + account.getBalance());
account.deposit(-20);
account.deposit(0);
account.withdraw(-5);
console.log("Balance: " + account.getBalance());
if (account.withdraw(120)) {
console.log("Withdrew all");
}
console.log("Balance: " + account.getBalance());
if (!account.withdraw(1)) {
console.log("Rejected");
}
TypeScript details worth knowing
#balanceagainstprivate balance. TypeScript also has aprivatekeyword, but it is checked only by the compiler and erased from the JavaScript. A#field is private at run time too. Outside the class,account.#balanceis a compile error (Property '#balance' is not accessible outside class 'BankAccount' because it has a private identifier), and in the compiled JavaScript it is a syntax error, so the program doesn't even start. Withprivate xin a class, readingp.xfrom outside also gets a compiler error, yet the compiled program runs and prints the value.- Private fields are hidden from enumeration. For an account created with 100,
Object.keys(account)is[]andJSON.stringify(account)is{}. Looking foraccount.balancegivesundefined, because no property of that name exists. - The one-line
if.if (amount <= 0) return;is anifwithout braces. Indeposit, a barereturnis valid because the return type isvoid. Inwithdraw, the guard returns a value. - Short-circuit
||. Inamount <= 0 || amount > this.#balance, the second comparison runs only when the first is false. - Types are not run-time checks. The
numberannotation stops the compiler from accepting a string, but nothing is checked once the code is compiled. If a caller bypasses the types with a cast,deposit("5" as any)on an account holding 100 makes the balance1005, because+=then joins strings.
Complexity
Every method does a fixed number of comparisons and at most one addition or subtraction, so each call takes O(1) time. An account stores one number, so the space is O(1).
Edge cases and common mistakes
- Using
>=in the withdrawal guard. This refuses the withdrawal of exactly the balance. The driver'swithdraw(120)on a balance of 120 must succeed and leave 0. - Forgetting the
amount <= 0check inwithdraw.withdraw(-5)would then pass the second condition and increase the balance by 5. - Zero. A deposit or withdrawal of 0 is rejected with
<= 0. Writing< 0would let the zero amounts through. The balance wouldn't change, butwithdraw(0)would returntrue. - Changing the balance before the guard. If
withdrawsubtracted first and checked afterwards, a refused request would still have changed the balance. NaN. Every comparison withNaNis false, so neither guard rejects it. Afterdeposit(NaN)on an account holding 100,getBalance()returnsNaN. The lesson's tests don't use it, but a real account would add a check such asNumber.isFinite(amount).- Decimal amounts.
numberis a double, so a balance built from0.1and a deposit of0.2reads0.30000000000000004. Money is often stored in whole cents to avoid this. - Forgetting
this.. Inside a method,#balanceon its own is not a variable. It must be writtenthis.#balance.
Testing
- A new account with 100:
getBalance()returns 100. - After
deposit(50), thenwithdraw(30):withdrawreturnedtrueand the balance is 120. withdraw(200)on a balance of 120 returnsfalseand the balance stays 120.deposit(-20),deposit(0)andwithdraw(-5)all leave the balance at 120.withdraw(120)returnstrueand the balance becomes 0, after whichwithdraw(1)returnsfalse.
