← All writing

The Art of Readable Code

Reading notes on making code easier to understand through precise naming, useful comments, clearer control flow and smaller expressions.

The Art of Readable Code

The Fundamental Theorem of Readability

Code should be written to minimize the time it would take for some else to understand it.

Part One: Surface-Level Improvememts

Chapter 2: Packing Information into Names

Choose Specific Words

Part of “packing information into names” is choosing words that are very specific and avoiding “empty” words.

It’s better to be clear and precise than to be cute.

for example, instead of Get, words like Fetch or Download might be better, depending on the context.

Avoid Generic Names Like tmp and retval

Pick a name that describes the entity’s value or purpose.

Loop Iterators, In some case, using more precise names may have helped.

Prefer Concrete Names over Abstract Names

For example, suppose you have an internal method named ServerCanStart(), which tests whether the server can listen on a given TCP/IP port. The name ServerCanStart() is somewhat abstract, though. A more concrete name would be CanListenOnPort(). This name directly describes what the method will do.

Attaching Extra Information to a Name

For example, suppose you had a variable that contained a hexadecimal string:

string id; // Example: "af84ef845cd8"

You might want to name it hex_id instead, if it’s important for the reader to remember the ID’s format.

Values with Units

Code
Start(int delay )              delay → delay_secs
CreateCache(int size )         size → size_mb
ThrottleDownload(float limit)  limit → max_kbps
Rotate(float angle)            angle → degrees_cw

Encoding Other Important Attributes

Code
password  plaintext_password
html      html_utf8
data      data_urlenc

How Long Should a Name Be?

Shorter Names Are Okay for Shorter Scope

Identifiers that have a small “scope” (how many other lines of code can “see” this name) don’t need to carry as much information.

Acronyms and Abbreviations

In our experience, project-specific abbreviations are usually a bad idea.

So our rule of thumb is: would a new teammate understand what the name means? If so, then it’s probably okay.

Throwing Out Unneeded Words

For instance, instead of ConvertToString(), the name ToString() is smaller and doesn’t lose any real information. Similarly, instead of DoServeLoop(), the name ServeLoop() is just as clear.

Use Name Formatting to Convey Meaning

For instance, constant values are of the form kConstantName instead of CONSTANT_NAME. This style has the benefit of being easily distinguished from #define macros, which are MACRO_NAME by convention.

Chapter 3: Names That Can’t Be Misconstrued

The best names are ones that can’t be misconstrued—the person reading your code will understand it the way you meant it, and no other way. Unfortunately, a lot of English words are ambiguous when it comes to programming, such as filter, length, and limit.

Before you decide on a name, play devil’s advocate and imagine how your name might be misunderstood. The best names are resistant to misinterpretation.

When it comes to defining an upper or lower limit for a value, max_ and min_ are good prefixes to use. For inclusive ranges, first and last are good. For inclusive/exclusive ranges, begin and end are best because they’re the most idiomatic.

When naming a boolean, use words like is and has to make it clear that it’s a boolean. Avoid negated terms (e.g., disable_ssl).

Beware of users’ expectations about certain words. For example, users may expect get() or size() to be lightweight methods.

Chapter 4: Aesthetics

Specifically, there are three principles we use:

1.Use consistent layout, with patterns the reader can get used to.

2.Make similar code look similar.

3.Group related lines of code into blocks.

Rearrange Line Breaks to Be Consistent and Compact

java
public class PerformanceTester {
    public static final TcpConnectionSimulator wifi =
        new TcpConnectionSimulator(
            500,   /* Kbps */
            80,    /* millisecs latency */
            200,   /* jitter */
            1      /* packet loss % */);
            
    public static final TcpConnectionSimulator t3_fiber =
        new TcpConnectionSimulator(
            45000, /* Kbps */
            10,    /* millisecs latency */
            0,     /* jitter */
            0      /* packet loss % */);
    public static final TcpConnectionSimulator cell =
        new TcpConnectionSimulator(
            100,   /* Kbps */
            400,   /* millisecs latency */
            250,   /* jitter */
            5      /* packet loss % */);
}

Use Column Alignment When Helpful

javascript
# Extract POST parameters to local variables
details  = request.POST.get('details')
location = request.POST.get('location')
phone    = equest.POST.get('phone')
email    = request.POST.get('email')
url      = request.POST.get('url')

Pick a Meaningful Order, and Use It Consistently

1.Order them from “most important” to “least important.”

2.Order them alphabetically.

Whatever the order, you should use the same order throughout your code.

Organize Declarations into Blocks

c
class FrontendServer {
 public:
     FrontendServer();
     void ViewProfile(HttpRequest* request);
     void OpenDatabase(string location, string user);
     void SaveProfile(HttpRequest* request);
     string ExtractQueryParam(HttpRequest* request, string param);
     void ReplyOK(HttpRequest* request, string html);
     void FindFriends(HttpRequest* request);
     void ReplyNotFound(HttpRequest* request, string error);
     void CloseDatabase(string location);
     ~FrontendServer();
};


class FrontendServer {
  public:
     FrontendServer();
     ~FrontendServer();
     // Handlers
     void ViewProfile(HttpRequest* request);
     void SaveProfile(HttpRequest* request);
     void FindFriends(HttpRequest* request);
     
     // Request/Reply Utilities
     string ExtractQueryParam(HttpRequest* request, string param);
     void ReplyOK(HttpRequest* request, string html);
     void ReplyNotFound(HttpRequest* request, string error);
     
     // Database Helpers
     void OpenDatabase(string location, string user);
     void CloseDatabase(string location);
}

Break Code into “Paragraphs”

python
def suggest_new_friends(user, email_password):
    # Get the user's friends' email addresses.
    friends = user.friends()
    friend_emails = set(f.email for f in friends)
    
    # Import all email addresses from this user's email account.
    contacts = import_contacts(user.email, email_password)
    contact_emails = set(c.email for c in contacts)
    
    # Find matching users that they aren't already friends with.
    non_friend_emails = contact_emails - friend_emails
    suggested_friends = User.objects.select(email__in=non_friend_emails)

Personal Style versus Consistency

We’ve worked on many projects where we felt like the team was using the “wrong” style, but we followed the project conventions because we knew that consistency is far more important.

Consistent style is more important than the “right” style.

Summary

1.If multiple blocks of code are doing similar things, try to give them the same silhouette.

2.Aligning parts of the code into “columns” can make code easy to skim through.

3.If code mentions A, B, and C in one place, don’t say B, C, and A in another. Pick a meaningful order and stick with it.

4.Use empty lines to break apart large blocks into logical “paragraphs.”

Chapter 5: Knowing What to Comment

The purpose of commenting is to help the reader know as much as the writer did.

What NOT to Comment

Reading a comment takes time away from reading the actual code, and each comment takes up space on the screen. That is, it better be worth it.

All of the comments in this code are worthless:

cpp
// The class definition for Account
class Account {
    public:
    // Constructor
    Account();
    // Set the profit member to a new value
    void SetProfit(double profit);
    // Return the profit from this Account
    double GetProfit();
};

Don’t comment on facts that can be derived quickly from the code itself.

Don’t Comment Just for the Sake of Commenting

eg: (bad)

cpp
// Find the Node in the given subtree, with the given name, using the given depth.
Node* FindNodeInSubtree(Node* subtree, string name, int depth);

(good)

cpp
// Find a Node with the given 'name' or return NULL.
// If depth <= 0, only 'subtree' is inspected.
// If depth == N, only 'subtree' and N levels below are inspected.
Node* FindNodeInSubtree(Node* subtree, string name, int depth);

Don’t Comment Bad Names—Fix the Names Instead

The name DeleteRegistry() sounds like a dangerous function (it deletes the registry?!). The comment “This doesn’t modify the actual registry” is trying to clear up the confusion.(bad)

cpp
// Releases the handle for this key. This doesn't modify the actual registry.
void DeleteRegistry(RegistryKey* key);

(good)

cpp
void ReleaseRegistryHandle(RegistryKey* key);

Coders often state this rule as good code > bad code + good comments.

Comment the Flaws in Your Code

cpp
// TODO: use a faster algorithm

// TODO(dustin): handle other image formats besides JPEG

When cooperating with ohters, we can comment with own nickname.

The important thing is that you should always feel free to comment on your thoughts about how the code should change in the future.

Comment on Your Constants

“Big Picture” Comments

One of the hardest things for a new team member to understand is the “big picture”—how classes interact, how data flows through the whole system, and where the entry points are.

This is exactly the type of information that should be included as high-level comments.

cpp
// This file contains helper functions that provide a more convenient interface to our
// file system. It handles file permissions and other nitty-gritty details.

A few well-chosen sentences are better than nothing at all.

Summary

What not to comment:

1.Facts that can be quickly derived from the code itself.

2.“Crutch comments” that make up for bad code (such as a bad function name)—fix the code instead.

Thoughts you should be recording include:

1.Insights about why code is one way and not another (“director commentary”).

2.Flaws in your code, by using markers like TODO: or XXX:.

3.The “story” for how a constant got its value

Put yourself in the reader’s shoes:

1.Anticipate which parts of your code will make readers say “Huh?” and comment those.

2.Document any surprising behavior an average reader wouldn’t expect.

3.Use “big picture” comments at the file/class level to explain how all the pieces fit together.

4.Summarize blocks of code with comments so that the reader doesn’t get lost in the details.

Chapter 6: Making Comments Precise and Compact

If you're going to write a comment at all, it might as well be precise—as specific and detailed as possible. On the other hand, comments take up extra space on the screen, and take extra time to read. So comments should also be compact.

Comments should have a high information-to-space ratio.

Keep Comments Compact

cpp
// The int is the CategoryType.
// The first float in the inner pair is the 'score',
// the second is the 'weight'.
typedef hash_map<int, pair<float, float> > ScoreMap;

cpp
// CategoryType -> (score, weight)
typedef hash_map<int, pair<float, float> > ScoreMap;

Avoid Ambiguous Pronouns

Describe Function Behavior Precisely

cpp
// Return the number of lines in this file.
int CountLines(string filename) { ... }

This comment isn’t very precise—there are a lot of ways to define a “line”. Here are some corner cases to think about:

• "" (an empty file)—0 or 1 line?

• "hello"—0 or 1 line?

• "hello\n"—1 or 2 lines?

• "hello\n world"—1 or 2 lines?

• "hello\n\r cruel\n world\r"—2, 3, or 4 lines?

cpp
// Count how many newline bytes ('\n') are in the file.
int CountLines(string filename) { ... }

Use Input/Output Examples That Illustrate Corner Cases

State the Intent of Your Code

Summary

1.Avoid pronouns like “it” and “this” when they can refer to multiple things.

2.Describe a function’s behavior with as much precision as is practical.

3.Illustrate your comments with carefully chosen input/output examples.

4.State the high-level intent of your code, rather than the obvious details.

5.Use inline comments (e.g., Function(/* arg = */ ... ) ) to explain mysterious function arguments. (out of date!)

6.Keep your comments brief by using words that pack a lot of meaning.

Part Two: Simplifying Loops and Logic

Chapter 7: Making Control Flow Easy to Read

Make all your conditionals, loops, and other changes to control flow as “natural” as possible—written in a way that doesn’t make the reader stop and reread your code.

The Order of Arguments in Conditionals

cpp
if (length >= 10) //easy to read
    
if (10 <= length) //unnatural

The Order of if/else Blocks

cpp
//better
if (a == b) 
{
 // Case One ...
} 
else 
{
 // Case Two ...
}

//worse
if (a != b) 
{
 // Case One ...
} 
else 
{
 // Case Two ...
}

1.Prefer dealing with the positive case first instead of the negative—e.g., if (debug) instead of if (!debug).

2.Prefer dealing with the simpler case first to get it out of the way. This approach might also allow both the if and the else to be visible on the screen at the same time, which is nice.

3.Prefer dealing with the more interesting or conspicuous case first.

Avoid do/while Loops

Returning Early from a Function

The Infamous goto

Minimize Nesting

Deeply nested code is hard to understand. Each level of nesting pushes an extra condition onto the reader’s "mental stack".

Removing Nesting Inside Loops

cpp
for (int i = 0; i < results.size(); i++) 
{
	if (results[i] != NULL) 
    {
		non_null_count++;
        if (results[i]->name != "") 
        {
			cout << "Considering candidate..." << endl;
 			...
 		}
	}
}

cpp
for (int i = 0; i < results.size(); i++) 
{
	if (results[i] == NULL) continue;
		non_null_count++;
	if (results[i]->name == "") continue;
		cout << "Considering candidate..." << endl;
	...
}

Chapter 8: Breaking Down Giant Expressions

Recent research suggests that most of us can only think about three or four “things” at a time. Simply put, the larger an expression of code is, the harder it will be to understand.

Break down your giant expressions into more digestible pieces.

Explaining Variables

The simplest way to break down an expression is to introduce an extra variable that captures a smaller subexpression.

python
if line.split(':')[0].strip() == "root":

# better one
username = line.split(':')[0].strip()
if username == "root":

Chapter 9: Variables and Readability

Specifically, there are three problems to contend with:

  1. The more variables there are, the harder it is to keep track of them all.
  2. The bigger a variable’s scope, the longer you have to keep track of it.
  3. The more often a variable changes, the harder it is to keep track of its current value.

Eliminating Control Flow Variables

java
boolean done = false;
while (/* condition */ && !done) 
{
    ...
    if (...) 
    {
        done = true;
        continue;
    }
}

while (/* condition */) 
{
    ...
    if (...) 
    {
		break;
    }
}

Shrink the Scope of Your Variables

We’ve all heard the advice to “avoid global variables.” This is good advice, because it’s hard to keep track of where and how all those global variables are being used.

Make your variable visible by as few lines of code as possible.

Moving Definitions Down

Prefer Write-Once Variables

Well, it’s even harder to think about variables that are constantly changing. Keeping track of their values adds an extra degree of difficulty.

The more places a variable is manipulated, the harder it is to reason about its current value.

Part Three: Reorganizing Your Code

• Extract “unrelated subproblems” that aren’t related to the primary goal of your program.

• Rearrange your code so it’s doing only one task at a time.

• Describe your code in words first, and use this description to help guide you to a cleaner solution.

Chapter 10: Extracting Unrelated Subproblems

As you’ll see, it’s an easy technique to apply but can improve your code substantially.

Pure Utility Code

There is a core set of basic tasks that most programs do, such as manipulating strings, using hash tables, and reading/writing files.

Other General-Purpose Code

Create a Lot of General-Purpose Code

They’re so basic and widely applicable that they are likely to be reused across projects. Codebases often have a special directory for code like this (e.g., util/) so that it can be easily shared.

General-purpose code is great because it’s completely decoupled from the rest of your project.

The more of your project you can break away as isolated libraries, the better, because the rest of your code will be smaller and easier to think about.

Project-Specific Functionality

Simplifying an Existing Interface

Reshaping an Interface to Your Needs

Summary

A simple way to think about this chapter is to separate the generic code from the projectspecific code. As it turns out, most code is generic.

Chapter 11: One Task at a Time

Code should be organized so that it’s doing only one task at a time.

Here’s the process we use to make code do “one task at a time”:

  1. List out all the “tasks” your code is doing. We use the word “task” very loosely—it could be as small as “make sure this object is valid” or as vague as “iterate through every node in the tree.”

  2. Try to separate those tasks as much as you can into different functions or at least different sections of code.

Tasks Can Be Small

Extracting Values from an Object

Summary

This chapter illustrates a simple technique for organizing your code: do only one task at a time.

If you have code that’s difficult to read, try to list all of the tasks it’s doing. Some of these tasks might easily become separate functions (or classes). Others might just become logical “paragraphs” within a single function. The exact details of how you separate these tasks isn’t as important as the fact that they’re separated. The hard part is accurately describing all the little things your program is doing.

Chapter 12: Turning Thoughts into Code

In this chapter, we’ll use a simple process that can help you code more clearly:

  1. Describe what code needs to do, in plain English, as you would to a colleague.
  2. Pay attention to the key words and phrases used in this description.
  3. Write your code to match this description.

Describing Logic Clearly

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.