Track 04 · Lesson 8 of 15Code that stays easy to change

Track 04 · Code that stays easy to change

Separation of concerns

Lesson 8 of 15· 6 min

Keep data, rules and presentation in different places, so each can change or be tested without the others.

Run the same tests on both

Run them, flip the switch, run again

CheckoutSummary.tsx

fetch("/api/cart")discount rulesJSX and classes
  • Not runSAVE10 on $100
  • Not runFLAT5 on $60
  • Not runFLAT5 on $40 (under minimum)
  • Not runUnknown code on $70

The rule only exists inside a rendered component, so every test has to build one.

CheckoutSummary.tsxWithout it
// The discount rule lives inside the component
export function CheckoutSummary() {
  const { data: cart } = useSWR("/api/cart", fetcher);
  const [code, setCode] = useState("");

  let total = cart?.subtotal ?? 0;
  if (code === "SAVE10") total = total * 0.9;
  if (code === "FLAT5" && total > 50) total = total - 5;

  return (
    <section className="rounded-xl border p-4">
      <Input value={code} onChange={(e) => setCode(e.target.value)} />
      <p className="text-lg font-semibold">${total.toFixed(2)}</p>
    </section>
  );
}

// To check one rule: mock the network, render a DOM, simulate typing
test("SAVE10 takes 10% off", async () => {
  server.use(http.get("/api/cart", () => HttpResponse.json({ subtotal: 100 })));
  render(<CheckoutSummary />);
  await userEvent.type(screen.getByRole("textbox"), "SAVE10");
  expect(await screen.findByText("$90.00")).toBeInTheDocument();
});

Three layers#

  • Data: where things come from. API calls, database queries, local storage.
  • Rules: what the business decides. Discounts, tax, permissions, validation. Pure functions where possible: data in, answer out.
  • Presentation: how it looks. Components, markup, styles.

When the discount rule is a plain function, testing it is one line: call it, check the answer. No React, no network, no waiting. When it lives inside a component, every test has to build the whole component first, and a test that waits on rendering can fail for reasons that have nothing to do with discounts.

The payoff#

Separated layers can be swapped independently: a new API, a redesign, a new discount type. You'll lean on this again in Identity and login, where the rules for who can do what must live on the server, not in the UI.

Check yourself

Why are tests for a discount rule inside a component slow and flaky?