There is a very satisfying moment when reading a technical book: I copy the example, run it and see exactly the promised result on screen. I allow myself a little celebration. Then comes the spoilsport question: if I change something, do I still know what I am doing?

That is also the question I keep in mind when writing. I want the reader to close the book and take away a way of reasoning along with the code. The author’s program has already had plenty of help: someone chose the data, prepared the context and guided every step. Outside the page, that level of hospitality is not guaranteed.

The small cruelty of removing a value

I take a simple example: the mean of three temperatures, 18, 20 and 22 degrees. Add the values, divide by three and get 20. Everyone agrees so far, including the thermometer. Before running the code, though, I want to explain why that calculation answers the question.

Then I start bothering the example. I leave it one temperature: the mean should equal that value. Finally, I remove all the readings. Here the book and the program need to help me decide what to do, because the mean of no temperatures is not a particularly mysterious temperature: there is simply no value to calculate.

I like this check because it makes me predict something. I write down my expected result, run the program and compare. If I am surprised, I have found the passage to revisit. Going back two pages now has a much clearer purpose than rereading everything and hoping for enlightenment.

When the example stops being hospitable

Now I move from temperatures to grades with different weights. Can I reuse the simple mean? That depends on what I want: if some grades should count more, I need a mean that accounts for their weights. The most familiar piece of code might be wrong for the new problem.

That is why I insist on variations in my books. I want to accompany the reader to the point where they can choose and explain their choice. Even when that choice means setting aside the example they have just learned.

My advice is to take time to make a little trouble for each example. Change a value, remove a condition, ask what happens at the boundary. If the program complains, all the better: we finally have something interesting to discuss.