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

Track 04 · Code that stays easy to change

S: Single responsibility

Lesson 3 of 15· 6 min

A module should have one reason to change. This is the S of SOLID and the foundation for most of the principles after it. Like every lesson in this track, it has a real case and a switch that shows the code without the principle, then with it.

How far does one change spread?

Pick a request, then flip the switch

A change request comes in. How far does it spread?

UserProfileCard.tsx 214 lines

Date formattingFetching and savingBio validationLayout and markup

0

Lines to re-check

0

Features that could break

Pick a change request to see how far it spreads.

UserProfileCard.tsxWithout it
// Fetching, formatting, validating and rendering, all in one place
export function UserProfileCard({ id }: { id: string }) {
  const [user, setUser] = useState<User | null>(null);
  const [bio, setBio] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    fetch(`/api/users/${id}`)
      .then((r) => r.json())
      .then((u: User) => { setUser(u); setBio(u.bio); });
  }, [id]);

  const joined = user
    ? new Date(user.createdAt).toLocaleDateString("en-US", { month: "short", year: "numeric" })
    : "";

  function save() {
    if (bio.length > 160) return setError("Bio is too long");
    if (bio.includes("http")) return setError("No links allowed");
    fetch(`/api/users/${id}`, { method: "PATCH", body: JSON.stringify({ bio }) });
  }

  if (!user) return <Spinner />;
  return (
    <Card className="space-y-4 p-6">
      <h2 className="text-xl font-semibold">{user.name}</h2>
      <p className="text-muted-foreground">Joined {joined}</p>
      <Textarea value={bio} onChange={(e) => setBio(e.target.value)} />
      {error && <p className="text-destructive">{error}</p>}
      <Button onClick={save}>Save</Button>
    </Card>
  );
}

"Reason to change" means "who asks for changes"#

Think about who sends change requests: the designer cares about the layout, the backend team moves endpoints, product changes the bio limit. When all of them edit the same file, every change risks breaking the others' work, and every change needs everything re-tested.

Split along those lines and each request touches one small file. The rest stays exactly as tested.

Don't overdo it#

Single responsibility doesn't mean "as many files as possible". A 40-line component with one job is fine as one file. You'll see the balance in the last lesson of this track, When they disagree.

Check yourself

A component fetches data, validates input and renders the layout. Design asks for tighter spacing. What's the risk?