Skip to Main Content
The Art of Readable Code
book

The Art of Readable Code

by Dustin Boswell, Trevor Foucher
November 2011
Intermediate to advanced content levelIntermediate to advanced
206 pages
4h 32m
English
O'Reilly Media, Inc.
Content preview from The Art of Readable Code

Chapter 8. Breaking Down Giant Expressions

image with no caption

The giant squid is an amazing and intelligent animal, but its near-perfect body design has one fatal flaw: it has a donut-shaped brain that wraps around its esophagus. So if it swallows too much food at once, it gets brain damage.

What does this have to do with code? Well, code that comes in “chunks” that are too big can have the same kind of effect. Recent research suggests that most of us can only think about three or four “things” at a time.[1] Simply put, the larger an expression of code is, the harder it will be to understand.

Key Idea

Break down your giant expressions into more digestible pieces.

In this chapter, we’ll go through various ways you can manipulate and break down your code so that it’s easier to swallow.

Explaining Variables

The simplest way to break down an expression is to introduce an extra variable that captures a smaller subexpression. This extra variable is sometimes called an “explaining variable” because it helps explain what the subexpression means.

Here is an example:

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

Here is the same code, now with an explaining variable:

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

Summary Variables

Even if an expression doesn’t need explaining (because you can figure out what it means), it can still be useful to capture that expression in a new variable. We call this a

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Five Lines of Code

Five Lines of Code

Christian Clausen
The Art of Clean Code

The Art of Clean Code

Christian Mayer

Publisher Resources

ISBN: 9781449318482Errata Page