Parameter Type Checking and Validation
What You'll Learn
You'll learn how to verify that the values passed into your functions are valid and handle situations where they aren't.
Why Validate Parameters?
Imagine you wrote a function calculateSquareRoot(number). What happens if someone passes -5 or the text "hello"? Your function might crash, produce nonsense, or corrupt data. Parameter validation means checking inputs before using them, so your function can respond gracefully to bad data.
Two Layers of Protection
Type Checking
First, ensure the parameter is the right type. In strongly-typed languages, the compiler often handles this automatically—passing a string where an integer is expected won't compile. In dynamically-typed languages, you check types at runtime using built-in tools.
Value Validation
Even correct types can carry invalid values. A function setAge(age) might require age to be non-negative. A divide(a, b) function must ensure b isn't zero.
Handling Invalid Inputs
When validation fails, you have choices:
- Return an error value (like
-1orNone) - Return a boolean success flag alongside the result
- Use default values when possible
- Raise an error/exception (covered later, but the concept is signaling "I can't continue")
- Document assumptions clearly so callers know their responsibilities
Example Pattern (Conceptual)
function divide(numerator, denominator):
// Type already enforced by language
// Now validate the VALUE
if denominator equals 0:
return error or special value
return numerator / denominator
Key Takeaway:
Always validate both the type and value of parameters at the start of your function to prevent errors and make your code robust and predictable.