Bitpath

Boss lesson · Unit 04

An order's lifecycle

Explicit states, legal moves, and undo

12 exercisesabout 3 min

What you practise

  • An order's lifecycle as explicit states and transitions
  • Actions as objects with undo
  • And when a pattern is more ceremony than help

Try a question from this lesson

Pick one

With separate paid, sent and cancelled flags, a bug once stored an order as both sent and cancelled. What happens to that bug with a single state field?

The ideas

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

Concept

One state, legal moves

Store one state, not three flags, and write the legal moves down as data.

The table is the whole lifecycle in one place: whatever is not listed is not allowed. No combination of fields can now describe an order that should not exist.

moves = {
    "new": ["paid", "cancelled"],
    "paid": ["sent", "cancelled"],
    "sent": [],
    "cancelled": [],
}
const moves = {
  new: ["paid", "cancelled"],
  paid: ["sent", "cancelled"],
  sent: [],
  cancelled: [],
};
type State =
  | "new" | "paid"
  | "sent" | "cancelled";

const moves: Record<State, State[]> = {
  new: ["paid", "cancelled"],
  paid: ["sent", "cancelled"],
  sent: [],
  cancelled: [],
};

TypeScript noteA union of string literals makes the compiler reject a misspelt state, and Record<State, State[]> makes it reject a table with a state left out.

Concept

Command

A command is an action turned into a value: an object that knows how to do one thing and how to reverse it.

Values can be kept in a list. A list of the commands that ran is a history, and undo is taking the last one off and running it backwards.

class Add:
    def __init__(self, n):
        self.n = n
    def run(self, total):
        return total + self.n
    def undo(self, total):
        return total - self.n
class Add {
  constructor(n) { this.n = n; }
  run(total) { return total + this.n; }
  undo(total) { return total - this.n; }
}
class Add {
  constructor(private n: number) {}
  run(total: number) {
    return total + this.n;
  }
  undo(total: number) {
    return total - this.n;
  }
}

JavaScript notedo is a reserved word in JavaScript, which is why the method is called run.

TypeScript notedo is a reserved word in JavaScript and TypeScript, which is why the method is called run.

9 more exercises in the app

  • 4× type the answer
  • 1× fill the blanks
  • 1× true or false
  • 1× order the lines
  • 1× multiple choice
  • 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.

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