Book Deep-Read · A Philosophy of Software Design · Chapter 18

Code Should be Obvious

A Philosophy of Software Design · Ch 18 · Code Should be Obvious · Ousterhout · 2nd ed 2021

中文 →

What is this chapter about?

You know things that just work at first sight: you push a door handle down and the door opens; elevator buttons are labeled with floor numbers. You also know things that trip you up: a door with a big pull handle that only opens if you push. Code is the same. Some code you understand at a glance, and your guess about it is right; other code you stare at for ages and still guess wrong. This chapter is about writing the first kind: obvious code.

A strange fact first

Programmers almost never think their own code is hard to read. The reason is simple: they carry all the background in their heads and fill in the gaps without noticing. It's like giving a friend directions: "turn left at the usual place." It's perfectly clear to you, and your friend has no idea where "the usual place" is. Only the reader can say whether something is clear.

Why the old world was hard

Code is written once but read by different people for years. Every shortcut the writer takes becomes a puzzle for the reader: a box holding "two things" without saying which is which; a program that says it has "finished" but keeps quietly running in the background. Readers guess from common sense, guess wrong, and a problem is planted.

How it works, intuitively

What it buys / how to choose

Readers save time, make fewer mistakes and change code with more confidence. The principle: code should be written for the reader's convenience, not the writer's. One honest cost: caring for the reader often means a bit more work for the writer, such as defining one more small data type or adding a few lines of explanation.

Remember it in one line

The reader decides whether code is clear; code is obvious when the reader's first guess is right.

Want the four coding habits that most often make code obscure, how "obvious" boils down to "does the reader have the information they need," and what Google's code review guide says? → Switch to Deep