AlgoViz

DRY

easy 40 min

Don't repeat yourself: every piece of knowledge has one home, and everything else asks that home.

Watch lesson4:18

Refactor

One home for the email rule and one for tax.

The point: a home is more than a helper function. It should be hard to go around it.

Implementation

Build the homes, then move the callers

Email and tax with one home each

A small value class. The check happens when the value is made, so a checked value cannot be confused with a plain string.

from __future__ import annotationsfrom dataclasses import dataclass@dataclass(frozen=True)class EmailAddress:    value: str    @classmethod    def parse(cls, raw: str | None) -> EmailAddress:        text = (raw or "").strip()        name, at, domain = text.rpartition("@")        parts = domain.split(".")        if not (at and name) or " " in text or len(parts) < 2 or "" in parts:            raise ValueError("email: expected name@domain")        return cls(name + "@" + domain.lower())

Lines 5 to 7

Frozen: the value cannot change after the check. Equality comes for free, so it can be a key in a dict.

1 of 5

Why it is built this way

  • A value class beats a helper function here: a method that takes EmailAddress cannot be called with an unchecked string.
  • The check is rough on purpose. A confirmation mail proves the rest.