Bitpath

Boss lesson · Unit 07

A bank

Accounts and transfers, with rules held by types where possible and by code where not

13 exercisesabout 3 min

What you practise

  • Accounts, transfers and a history, rules enforced by types where possible and by code where not
  • A first design reviewed and improved

Try a question from this lesson

Pick one

A first design: an account is a plain object. The bank has one rule: never below zero. What does this print?

TypeScript
type Account = {
  owner: string;
  balance: number;
};
const acc: Account = {
  owner: "Ada", balance: 50,
};
acc.balance = acc.balance - 80;
console.log(acc.balance);

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

A second design

Make the account a class and its balance private. Now the only way to change the balance is through methods, and the methods can hold the rules.

A getter lets the outside read the balance without being able to write it. The owner is readonly: an account does not change hands.

TypeScript
class Account {
  private balance = 0;
  constructor(readonly owner: string) {}

  get total(): number {
    return this.balance;
  }
  deposit(amount: number) {
    this.balance += amount;
  }
}

Concept

A history the compiler checks

A bank keeps a record of everything that happened. Each entry has a kind, and a literal union says exactly which kinds exist.

This rule is one the types can hold: an entry of a made-up kind cannot even be written down.

TypeScript
type Entry = {
  kind: "deposit" | "withdraw";
  amount: number;
};
const log: Entry[] = [];
log.push({ kind: "deposit", amount: 50 });

// log.push({ kind: "gift", amount: 5 });
// rejected: "gift" is not a kind

10 more exercises in the app

  • 2× order the lines
  • 3× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy