PythiloLesson 8 of 15 · progress kept in this browser

Duplication and when to remove it

When the same rule is copied into three functions, every fix has to be made three times, and one copy always gets missed. Write the rule once and pass in what varies.

def labelled(items, label):
    names = ", ".join(sorted(items))
    return f"{label}: {names or 'none'}"

print(labelled({"tea", "jam"}, "Bought"))
print(labelled(set(), "Returned"))

Not all similar code is duplication, though. Two functions that look alike today but change for different reasons, say a tax rule and a shipping rule that both happen to multiply by 1.2, should stay apart. Merging them means that changing one breaks the other.

A useful habit is the rule of three: tolerate a second copy, and extract when the third arrives, because by then you can see which parts vary. Name the shared function after the rule it expresses, not after the code it happens to contain.

Your task

Extract bulk_price(price, qty, min_qty, discount): price times qty, less the fraction discount when qty is at least min_qty, rounded to cents. Make book_price, pen_price and paper_price one-line calls to it, which also fixes the copy that forgot to round.