Chapter 8. Breaking Down Giant Expressions
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. 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.
In this chapter, we’ll go through various ways you can manipulate and break down your code so that it’s easier to swallow.
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(':').strip() == "root": ...
Here is the same code, now with an explaining variable:
username = line.split(':').strip() if username == "root": ...
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