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. ...