Bitpath

Lesson 2 · Unit 01

Reasons to change

One job per unit, and new cases as new code

11 exercisesabout 3 min

What you practise

  • One responsibility per unit, open to extension without editing, subtypes that keep the promises of their parents, shown as before-and-after

Try a question from this lesson

Pick one

Three requests arrive: a new tax rule, a new page layout, a new mail provider. How many of them force an edit to this class?

class Report:
    def total(self, rows):
        return sum(rows)
    def html(self, rows):
        t = self.total(rows)
        return "<b>" + str(t) + "</b>"
    def send(self, rows):
        print("mail:", self.html(rows))
class Report {
  total(rows) {
    let t = 0;
    for (const r of rows) t += r;
    return t;
  }
  html(rows) {
    const t = this.total(rows);
    return "<b>" + t + "</b>";
  }
  send(rows) {
    console.log("mail:", this.html(rows));
  }
}
class Report {
  total(rows: number[]): number {
    let t = 0;
    for (const r of rows) t += r;
    return t;
  }
  html(rows: number[]): string {
    const t = this.total(rows);
    return "<b>" + t + "</b>";
  }
  send(rows: number[]): void {
    console.log("mail:", this.html(rows));
  }
}

The ideas

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

Concept

One reason to change

A unit of code should have one responsibility: one group of people, or one kind of decision, that can ask it to change.

The test is not "is it short?" but "who would ask me to edit this?". If the honest answer has an "and" in it, there are two units hiding in one.

Concept

New case, new code

Code is open for extension and closed for modification when a new case arrives as an addition, with no edit to what already works.

The lightest way: a table from kind to function. The lookup never changes. Adding a kind is adding an entry.

rates = {
    "post": lambda kg: 2 * kg,
    "drone": lambda kg: 10 + kg,
}

def cost(kind, kg):
    return rates[kind](kg)
const rates = {
  post: (kg) => 2 * kg,
  drone: (kg) => 10 + kg,
};

function cost(kind, kg) {
  return rates[kind](kg);
}
type Rate = (kg: number) => number;

const rates: Record<string, Rate> = {
  post: (kg) => 2 * kg,
  drone: (kg) => 10 + kg,
};

function cost(kind: string, kg: number) {
  return rates[kind](kg);
}

Python noteAn unknown kind now raises KeyError instead of quietly returning 0. A loud failure is the better default.

TypeScript noteRecord<string, Rate> is an object whose keys are strings and whose values are all Rate functions, so (kg) => 2 * kg needs no annotation.

8 more exercises in the app

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

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