
"Do not overcrowd your functions with logic for four or five different things. A function should do a single thing, and it should do it well, and the name of the function should clearly tell you what your function does. If you are unsure about whether some piece of code should be a single function or multiple functions, it's best to err on the side of too many functions. That is because a function is a modular piece of code, and the smaller your functions are, the easier it is to compose them together to create more complex behaviours."
"Consider the function process_order defined below, an exaggerated example that breaks these best practices to make the point clearer. While it is not incredibly long, it does too many things: def process_order(order): # Validate the order: for item, quantity, price in order: if quantity <= 0: raise ValueError(f"Cannot buy 0 or less of {item}.") if price <= 0: raise ValueError(f"Price must be positive.") # Write the receipt: total = 0 with open("receipt.txt", "w") as f: for item, quantity, price in order: # This week, yoghurts and batteries are on sale. if "yoghurt" in item: price *= 0.8 elif "batteries" in item: price *= 0.5 # Write this line of the receipt: partial = price * quantity f.write(f"{item:>15} --- {quantity:>3} x {price:>6.2f} : ${partial:>6.2f} ") total += partial f.write(" " * 27 + f"Total : ${total:>6.2f} ") order = [ ("greek yoghurt", 2, 4.57), ("AAA batteries", 1, 9.99), ("AA batteries""
Knowing def is only the first step to effective function use. Functions should follow single-responsibility: each function performs one task and its name should describe that task. Prefer splitting uncertain or multi-step code into multiple smaller functions, because smaller functions are modular, easier to test, maintain, and compose into more complex behaviors. Avoid packing validation, business logic, formatting, and I/O into a single function. Break responsibilities into validation, transformation, formatting, and output functions to improve clarity, reusability, and correctness while reducing complexity.
Read at Mathspp
Unable to calculate read time
Collection
[
|
...
]