Defensive Programming — Explained with Examples
Defensive programming is a practice where code anticipates and handles potential errors, invalid inputs, and unexpected states at every boundary.
Defensive Programming assumes that inputs will be invalid, external services will fail, and assumptions will be wrong. It adds validation, error handling, assertions, and sanity checks to ensure the system degrades gracefully rather than crashing or corrupting data.
Why Defensive Programming Matters
Production systems face conditions that unit tests don’t: null values from APIs, malformed data from legacy systems, network timeouts, memory limits. Defensive programming turns unpredictable failures into predictable, handled outcomes. It separates “normal” code from “something went wrong” code.
Real-World Analogy
A car’s safety features: seatbelts, airbags, anti-lock brakes, crumple zones. The driver doesn’t plan to crash, but the car is designed defensively. Similarly, defensive programming adds safety nets for when things go wrong, even if you expect them to go right.
Example: Defensive Programming
# Non-defensive — crashes on any unexpected input
def divide(a, b):
return a / b # ZeroDivisionError if b == 0# Defensive — handles edge cases
def divide(a, b):
if not isinstance(a, (int, float)):
raise TypeError(f"a must be a number, got {type(a).__name__}")
if not isinstance(b, (int, float)):
raise TypeError(f"b must be a number, got {type(b).__name__}")
if b == 0:
raise ValueError("Division by zero is not allowed")
if abs(a) > 1e15 or abs(b) > 1e15:
print("Warning: large numbers may lose precision")
return a / b
# Usage with defensive checks
try:
result = divide(10, "not a number")
except TypeError as e:
print(f"Defensive check caught: {e}")
try:
result = divide(10, 0)
except ValueError as e:
print(f"Defensive check caught: {e}")
try:
result = divide(10, 3)
print(f"Result: {result:.2f}") # Output: Result: 3.33
except (TypeError, ValueError) as e:
print(f"Error: {e}")Related Terms
Fail Fast, Robustness Principle, Principle of Least Privilege
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro