Making Methods Robust by Checking Their
Inputs
Course: Software Construction and Development
Topic: Defensive Programming – Input Validation in Methods
1. What Is "Making Methods Robust by Checking Their Inputs"?
When we say "making methods robust by having them check their inputs", we mean:
Ensuring that every method (function) in a program verifies the correctness and validity
of the data it receives before it processes that data.
This technique is part of defensive programming writing code that defends itself from
errors or misuse.
2. Why Do We Use This Approach?
Here’s why input checking is critical:
- Prevents crashes (e.g., divide-by-zero)
- Avoids logical bugs
- Improves security
- Ensures data integrity
- Helps debugging
- Increases code reusability
3. Where Do We Use This?
Use input validation anywhere a method receives input, especially:
- User input from UI
- Input from another function
- External sources (files, APIs)
- Data from databases or services
Important in: Banking, e-commerce, healthcare, authentication systems.
4. What Should Be Checked?
When writing a method, validate inputs such as:
- Presence (not None or empty)
- Type (e.g., int, str)
- Range (acceptable limits)
- Format (e.g., email)
- Business rules (e.g., password rules)
5. Examples
Example 1: Basic Input Validation (Division Function)
def divide(a, b):
# Check if 'b' is zero to avoid division error
if b == 0:
return "Error: Cannot divide by zero."
return a / b
# Calling the function
print(divide(10, 2)) # Output: 5.0
print(divide(10, 0)) # Would crash if not checked, but now returns error
Example 2: String Input and Null Check
def greet_user(name):
# Check for empty or None input
if not name:
return "Error: Name cannot be empty."
return f"Hello, {name}!"
print(greet_user("Alice")) # Output: Hello, Alice!
print(greet_user("")) # Error handled gracefully
Example 3: Type and Value Range Validation
def set_age(age):
# Check that age is a number
if not isinstance(age, int):
return "Error: Age must be an integer."
# Check that age is within a valid human range
if age < 0 or age > 130:
return "Error: Invalid age range."
return f"Age set to {age}"
print(set_age(25)) # Output: Age set to 25
print(set_age(-5)) # Invalid age
print(set_age("twenty")) # Wrong type
Example 4: Email Format Check
def is_valid_email(email):
# Very basic email format check
if "@" not in email or "." not in email:
return "Error: Invalid email format."
return "Email is valid."
print(is_valid_email("[email protected]"))
print(is_valid_email("invalidemail.com")) # Missing '@'
Case Study: ATM Withdrawal System
Problem: No Input Check
def withdraw(balance, amount):
return balance - amount # This can go negative or accept invalid data
print(withdraw(1000, 1500)) # Balance becomes -500, no warning
Solution: Robust Method with Input Validation
def withdraw(balance, amount):
# Type checks
if not isinstance(balance, (int, float)) or not isinstance(amount, (int, float)):
return "Error: Invalid data type."
# Logical checks
if amount <= 0:
return "Error: Withdrawal amount must be positive."
if amount > balance:
return "Error: Insufficient balance."
return f"Withdrawal successful. Remaining balance: {balance - amount}"
print(withdraw(1000, 500)) # Valid withdrawal
print(withdraw(1000, 1500)) # Error: Insufficient balance
print(withdraw(1000, -100)) # Error: Negative withdrawal
print(withdraw(1000, "abc")) # Error: Wrong type
7. Best Practices
- Validate inputs early
- Use clear error messages
- Never trust external input
- Raise exceptions if needed
- Use helper functions for validations
8. Security and Safety
Input checking improves:
- Security (protects against malicious input)
- Safety (important for critical systems like medical or aviation software)