Recipe
Turn repeated code into a function
Use when: the same few lines appear in two places, or one block of code does a job you can name
Goal: one small, named, documented, checked function used everywhere the code was
Taught in Designing functions
Quick recipe
-
1
Pick the lines that do one job you can name in a sentence without "and".
Example
round(price * 1.2, 2), typed in three places: "add 20% tax".Why: a function with one clear job is easy to name, check and reuse.
-
2
The values that change between copies become parameters; the value the rest of the code needs becomes the return value.
Example
pricevaries, so it's the parameter; the taxed price is returned.Why: parameters and
returnare the function's whole connection to the outside, with no hidden globals. -
3
A verb for an action, the value's name for a calculation, a question for yes or no. Add defaults for settings that rarely change.
Example
def with_tax(price, rate=0.2):Why: a good name makes every call site explain itself.
-
4
One line, as a command, saying what comes back.
Example
"""Return price with tax added, rounded to cents."""Why:
help()and your editor show it to everyone who calls the function. -
5
Write two or three asserts with answers worked out by hand, then swap every copy of the old lines for a call.
Example
assert with_tax(10) == 12.0, thentotal = with_tax(price)in all three places.Why: the checks prove the function matches the code it replaces, before anything depends on it.