Course contentsShow
← Software Engineering
Lesson 176 of 1,9335. Software Design PrinciplesFree lesson

Fail Fast and Defensive Programming

Learn when to validate inputs aggressively and fail immediately versus when to handle errors gracefully.

Fail Fast and Defensive Programming

You'll learn: When to catch problems immediately at their source versus when to handle errors gracefully and continue.

Two Philosophies for Error Handling

These are two complementary approaches to dealing with invalid inputs and unexpected conditions:

Fail Fast means detecting problems as early as possible and stopping immediately. If something is wrong, throw an error right away rather than letting bad data propagate through your system. Think of it like a smoke detector—it alerts you the moment it detects danger, not after the house burns down.

Defensive Programming means anticipating problems and handling them gracefully. You add checks, validations, and fallback logic to prevent failures from spreading. Think of it like wearing a seatbelt—you prepare for problems even if you hope they never happen.

When to Use Each

Use Fail Fast when:

  • Receiving inputs at system boundaries (function parameters, API requests)
  • A problem indicates a programming error (not user error)
  • Continuing would cause worse problems or corrupt data
  • You want immediate feedback during development

Use Defensive Programming when:

  • Dealing with external systems or user input you can't control
  • Graceful degradation is better than complete failure
  • Recovery is possible and sensible

The Balance

The best code often uses both: fail fast on inputs you control (catching bugs early), but defend against external chaos you don't control. Validate aggressively at boundaries, then trust your validated data internally.

Key Takeaway: Fail fast to catch bugs immediately during development; use defensive programming to handle unpredictable external conditions gracefully. Both prevent small problems from becoming disasters.