{
    "slug": "defensive_programming",
    "term": "Defensive Programming",
    "category": "quality",
    "difficulty": "intermediate",
    "short": "Writing code that anticipates and handles invalid inputs, unexpected states, and failures gracefully.",
    "long": "Defensive programming assumes that callers will pass invalid data, external services will fail, and unexpected states will occur. Defences include: validating all input at trust boundaries, checking postconditions of external calls, handling all branches of switch/match, using guard clauses to reject invalid state early, and writing tests for edge cases. Taken too far, defensive programming produces code cluttered with redundant checks — balance it with Design by Contract, which makes assumptions explicit rather than defending against everything everywhere.",
    "aliases": [
        "defensive coding",
        "fail-safe programming",
        "input validation mindset"
    ],
    "tags": [
        "principles",
        "quality",
        "error-handling"
    ],
    "misconception": "Defensive programming means validating every input with the same intensity. It means calibrating defences to trust level — external input gets maximum validation, internal module calls rely on contracts and tests rather than redundant runtime checks that obscure the code.",
    "why_it_matters": "Defensive programming assumes inputs and system state will be invalid and handles it explicitly — it converts silent failures into detectable, traceable exceptions or errors.",
    "common_mistakes": [
        "Not validating method arguments — passing null or out-of-range values causes failures far from the source.",
        "Catching Exception too broadly and suppressing errors instead of handling them specifically.",
        "Defensive checks at every layer instead of trusting validated input from the boundary — creates noise.",
        "Not using PHP type declarations and strict_types=1 which provide free defensive checks at the language level."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "fail_fast",
        "design_by_contract",
        "input_validation",
        "guard_clause"
    ],
    "prerequisites": [
        "input_validation",
        "error_handling",
        "design_by_contract"
    ],
    "refs": [
        "https://en.wikipedia.org/wiki/Defensive_programming"
    ],
    "bad_code": "function divide(int $a, int $b): float {\n    return $a / $b; // crashes with division by zero, no guard\n}",
    "good_code": "function divide(int $a, int $b): float {\n    if ($b === 0) {\n        throw new \\DivisionByZeroError('Divisor cannot be zero');\n    }\n    return $a / $b;\n}\n\n// For value objects, validate in constructor so callers can't create invalid state:\nreadonly class Divisor {\n    public function __construct(public int $value) {\n        if ($value === 0) throw new \\DivisionByZeroError();\n    }\n}",
    "quick_fix": "Validate all inputs at system boundaries (HTTP request, queue message, file read) and use guard clauses to reject invalid state early — trust nothing from outside your module",
    "severity": "medium",
    "effort": "medium",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/defensive_programming",
        "html_url": "https://codeclaritylab.com/glossary/defensive_programming",
        "json_url": "https://codeclaritylab.com/glossary/defensive_programming.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Defensive Programming](https://codeclaritylab.com/glossary/defensive_programming) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/defensive_programming"
            }
        }
    }
}