3.4. Code Communicates

A primary purpose of code is communication. You are communicating with the computer, telling it what operations to perform. However, you are also communicating with the reader, showing him the steps you are taking to complete an operation. The most important issues to communicate are what are you doing and why you are doing it, not how you are doing it.

Code should communicate its purpose and your intention. On at least one level, code should read like a book, albeit one with stilted syntax. The client should be able to read the code to see if it follows the logic that he expressed in the requirements. The details of the implementation should be relegated to deeper levels.

When reading code, it is often difficult to determine intent. If the writer did not take particular care to make his intent clear, it might be buried in the details. The "micromanagement" of details can hide the flow of the logic.

For example:

    if (a_customer.has_late_rental (  ))
        a_customer.suspend_rental_privilege(  );

This code does not show how the suspension of rental privileges is recorded. It states why the person is being suspended (because of a late rental). The client should be able to follow the logic involved, without getting buried in implementation details.

COMMUNICATE WITH YOUR CODE[*]

Your code should communicate its purpose and intent.

[*] See Literate Programming by Donald Knuth (Center for the Study of Language and Information—Lecture Notes 1992) and The Elements of ...

Get Prefactoring now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.