QA
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→

More Software Engineering Principles Interview Questions

Beginner LevelSoftware Engineering Principles

Explain the 5 SOLID Principles of Object-Oriented Software Design with practical refactoring examples.

Beginner LevelSoftware Engineering Principles

What are DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and YAGNI (You Aren't Gonna Need It)?

Beginner LevelSoftware Engineering Principles

Why is Composition Over Inheritance a fundamental object-oriented design principle?