Defensive programming practices - Time & Space Complexity
When writing defensive code, we add checks and safeguards to avoid errors.
We want to see how these extra checks affect how long the program takes to run.
Analyze the time complexity of the following code snippet.
int safe_sum(int *arr, int size) {
if (arr == NULL || size <= 0) {
return 0; // Defensive check
}
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
This code sums numbers in an array but first checks if the input is valid to avoid errors.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds each array element.
- How many times: It runs once for each element in the array (size times).
The time to run grows directly with the number of elements because each one is added once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows steadily as the input grows, no surprises from the checks.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items to add.
[X] Wrong: "Adding defensive checks makes the program much slower for big inputs."
[OK] Correct: The checks run only once and do not grow with input size, so they don't change the main growth pattern.
Understanding how safety checks affect performance shows you care about writing reliable code that still runs efficiently.
"What if we added a nested loop inside the for-loop to check each element against all others? How would the time complexity change?"