In this lesson, you will learn how to design predictable and reusable functions by ensuring they behave consistently every time they are called.
The Foundation of Predictability
A predictable function is one that acts like a mathematical operation: if you provide the same input, you should always receive the same output. When a function relies on variables outside of its local scope—or changes the state of the program—it becomes "brittle." If that external state changes, your function’s behavior changes unexpectedly, making it difficult to track down bugs.
Designing for Reusability
To make a function reusable, it should perform one specific task and remain independent of its surroundings. Instead of letting a function "reach out" to grab global variables, pass all necessary data through parameters. This allows you to drop that function into any part of your codebase, knowing exactly how it will react based solely on the arguments provided.
Consider this example of a predictable, reusable function:
# A predictable function: only uses input arguments
def calculate_discount(price: float, rate: float) -> float:
return price * (1 - rate)
# This is reusable because it doesn't depend on global variables
# like 'current_user_level' or 'store_settings'.
item_price = 100.0
discounted = calculate_discount(item_price, 0.2)
Avoiding "Hidden" Dependencies
If you wrote calculate_discount to look at a global variable DISCOUNT_RATE, the function would be unpredictable. If someone else changed that global variable in another part of the program, your function would start returning different values for the same item_price input. By avoiding global state, you ensure that the function's logic is self-contained.
When you design functions that receive all they need through arguments and rely only on local calculations, you create "black boxes" that are easy to test, reuse across different projects, and debug because their behavior is entirely contained within their own definition.
Key Takeaway: Design functions that rely only on their parameters to produce a return value, ensuring they behave the same way every time they are called, regardless of where they are used in your program.