Beginner LevelSoftware Engineering Principles
What is Defensive Programming and how do assertions and precondition checks work?
❓ Interview Prompt: Explain Defensive Programming, precondition checks, invariants, postconditions, and using runtime assertions.
Defensive Programming is a design practice intended to ensure continuing function of a piece of software under unforeseen execution circumstances:
Key Techniques:
1
Precondition Checks: Validate input parameters before executing function logic ('if (!id) throw ...').
2
Assertions: Verify internal program assumptions during execution ('console.assert(balance >= 0)').
3
Sanitize Inputs: Neutralize malformed inputs before processing.
Code Implementation Example
typescript
function calculateAverage(numbers: number[]): number {
// Precondition Check: Protect against division by zero!
if (!numbers || numbers.length === 0) {
throw new Error('Precondition Failed: Array must contain at least one element.');
}
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
return sum / numbers.length;
}💡Adding input precondition checks in defensive programming.
🎯 Interview Key Takeaway
Apply defensive programming and precondition checks to prevent invalid inputs from corrupting application state.
#Defensive Programming#Assertions#Validation#Beginner
Back to all Software Engineering Principles Questions→