Concept

Defensive Programming

Definition

Defensive programming is the stance of treating every input, caller, and external system as potentially wrong. Rather than assuming data will be well formed and dependencies will behave, defensive code checks, validates, and prepares to handle the unexpected.

The Pragmatic Programmer authors summarize the attitude as being pragmatically paranoid: you cannot guarantee other code is correct, so you protect your own component against everyone else, including your past self.

Why it matters

How it works

The core technique is to validate at boundaries: check arguments on entry to a function, sanitize external input, and verify the results of calls into systems you do not control. When something is wrong, fail fast with a clear error rather than limping forward in a broken state.

Defensiveness has limits. The book pairs it with Design by Contract, which says that within a system you and your collaborators agree on responsibilities, so you need not re-check everything everywhere. The judgment call is where to be paranoid, typically the edges of your trust boundary, and where to rely on the contract.

Where it goes next

Continue exploring

Tags