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

Define Errors Out of Existence

A Philosophy of Software Design · Ch 10 · Define Errors Out of Existence · Ousterhout · 2nd ed 2021

中文 →

What is this chapter about?

You tap "delete" on a photo that is already gone. Should your phone pop up "Error: photo does not exist," or just quietly say "Deleted"? Programs face this choice everywhere. Many people believe more errors means more rigor. This chapter says: every new kind of "error" is a chore that everyone using your code must deal with; the best error handling is making the error impossible in the first place.

An analogy

You ask someone at home to "turn off the light." It is already off. A sensible person says "done," not "Report: the light is already off, unable to perform switch-off." What you wanted was the result, a dark room, not the act of flipping a switch. Phrase the request as a result, and the "error" vanishes.

Why the old way is hard

Code that handles surprises almost never runs in daily life, so it is where unnoticed mistakes hide. Worse, once a part announces "I might fail this way," everyone who uses it must write their own response. Ten users means ten responses, and ten places to get it wrong.

How it works, intuitively

What it buys you / how to choose

Users of your code have fewer things to worry about, so there are fewer chances to slip. The test is simple: if the user found out about this error, could they do anything useful? If not, don't put it in front of them. One honest cost: don't overdo it. If the user truly needs to know (say, a message really didn't arrive), hiding it is lying to them.

One line to remember

Before you report an error, ask whether a better definition could make it not exist at all.

Want to see why exceptions are a major source of complexity, the four techniques for reducing exception handling, the Unix file-deletion and Python slicing examples, and where "hiding too much" begins? → Switch to Deep