Defensive Programming: Check Before You Commit

Software receives values from users, files, networks, and other functions. Those values may be missing, malformed, outside an allowed range, or unsuitable for the current operation. Defensive programming means anticipating such conditions and handling them deliberately so that the program protects its data and produces a meaningful outcome. You use it when an unchecked assumption could cause an invalid calculation, excessive resource use, or an incorrect state change.

Check what an operation needs

Begin by identifying the conditions that make an operation meaningful. A quantity might need to be an integer, positive, within a per-request limit, and available in stock. Checking only one condition does not establish the others. A value can have the correct type while still being unsuitable.


Example: A retry setting of -3 is an integer, but a program that allows zero through five retries should reject it. Silently replacing it with zero changes the request; that is appropriate only if the specified behaviour explicitly permits that correction.


An early guard clause is a check near the beginning of an operation that exits when a required condition fails. Put guards before the actions they protect. Check that an index is valid before accessing a list, and check a divisor before dividing by it.


Input condition

Defensive response

Mistake to avoid

Wrong type or missing value

Reject or apply a specified conversion

Assuming every value supports the same operations

Outside the allowed range

Report the failed requirement

Checking only the upper endpoint

Exceeds available resources

Refuse before allocating or changing state

Discovering the shortage after an update

Valid under every required check

Continue with the operation

Treating one successful check as sufficient



Guard resource use

A valid-looking request can still demand more memory, time, stock, or credit than the program allows. Type checks therefore need operational limits.


Suppose a purchase requests an integer quantity qq, has a per-request limit LL, and spends from an integer balance BB. Each item costs pp units of currency. With B≥0B \geq 0, p>0p > 0, and sufficient stock, acceptance requires


1≤q≤min⁡(L,⌊Bp⌋).1 \leq q \leq \min\left(L,\left\lfloor\frac{B}{p}\right\rfloor\right).


The floor operation keeps the affordable quantity whole. Check the assumptions before evaluating the expression: dividing by a zero price would make the check itself unsafe.


In languages with fixed-width integers, multiplying a large requested quantity by its price can exceed the representable range. For nonnegative integer quantities and a positive price, comparing qq with ⌊B/p⌋\lfloor B/p\rfloor avoids that multiplication during the affordability check.



Preserve valid state

Rejected requests should leave protected state unchanged unless the specification explicitly requires a different effect. Calculate proposed results in temporary values, check them, and then apply the related changes together. A rejected purchase should not remove credit while leaving stock untouched.


A flow diagram shows validation leading either to safe rejection or to computation followed by a combined state update.


Checks also have a lifetime. If you retain a caller's mutable list, the caller may change it after validation. A defensive copy can preserve the checked values. Copying only the outer list is insufficient when both lists still contain the same mutable records. Copy the required nested data too, or retain validated immutable values.


Finally, distinguish expected failures from programming defects. Report an anticipated unreadable file or invalid input clearly. Catching every exception and returning a normal-looking result can conceal a defect and make incorrect data appear trustworthy. Failure handling must preserve the meaning of success.

What to remember

  • Check type, range, and operational limits before using a value.
  • Make rejection explicit and preserve protected state.
  • Prepare related updates before committing them.
  • Ensure retained data cannot invalidate an earlier check through later mutation.

Example: Protecting a Print Kiosk Balance

A print kiosk charges 35 cents per page and accepts requests containing 1 through 60 pages per job, inclusive. A user has a balance of 2750 cents, and the kiosk has 48 available sheets. Each page uses one sheet. The requested page count must be an exact Python integer; text, floating-point values, and booleans are rejected without conversion.


Model only the returned balance and sheet count. The stored values are trusted nonnegative integers, and no concurrent changes occur. A rejected request returns the original state. Each part starts from the original balance and sheet count.


a) What is the largest page count the kiosk can accept?


First check the independent upper limits. The job limit is 60 pages, and the available stock is 48 sheets. The balance can pay for ________, found by dividing the balance by the positive price and rounding down.


⌊2750 cents35 cents/page⌋=⌊78.571…⌋=78 pages.\left\lfloor\frac{2750\ \text{cents}}{35\ \text{cents/page}}\right\rfloor =\lfloor78.571\ldots\rfloor=78\ \text{pages}.


A request must satisfy every limit, so use the smallest upper bound.


qmax⁡=min⁡(60,48,78)=48 pages.q_{\max}=\min(60,48,78)=48\ \text{pages}.


The largest accepted request is 48 pages. Affordability alone would permit a larger request, but there are not enough sheets for it.


b) A user requests 24 pages. Determine whether the request is accepted and give the returned balance and sheet count.


The value 24 is an exact integer, is positive, does not exceed the 60-page job limit, and does not exceed the 48 available sheets. The charge is ________.


Charge=24 pages×35 cents/page=840 cents.\text{Charge}=24\ \text{pages}\times35\ \text{cents/page}=840\ \text{cents}.


The charge is no greater than the 2750-cent balance, so every acceptance condition holds. A candidate state is a proposed set of updated values prepared before committing an operation. Compute both proposed values from the same original state.


Bnew=2750−840=1910 cents,Snew=48−24=24 sheets.\begin{aligned} B_{\text{new}}&=2750-840=1910\ \text{cents},\\ S_{\text{new}}&=48-24=24\ \text{sheets}. \end{aligned}


The request is accepted, returning 1910 cents and 24 sheets. Both values remain nonnegative, providing a useful check on the calculation.


c) Explain what happens for the separate requests "12" and 49. Then write a function that returns acceptance status, balance, and sheet count without changing state on rejection.


The value "12" has the input type ________, so it is rejected before numerical comparisons. The integer 49 passes the positive-quantity and per-job checks. Its proposed charge would be ________, which is affordable.


49 pages×35 cents/page=1715 cents.49\ \text{pages}\times35\ \text{cents/page}=1715\ \text{cents}.


However, 49 pages require more than the available 48 sheets, so that request is also rejected. Safe rejection means refusing an invalid operation while preserving the protected state required by the specification. Both requests therefore return rejected, 2750 cents, and 48 sheets.


The function checks the type before applying numerical operations. It then checks the allowed range, stock, and affordability. Only a request that passes every guard reaches the calculation of updated values.


Python
def submit_job(q, balance, sheets):
    if type(q) is not int:
        return False, balance, sheets
    if not (1 <= q <= 60):
        return False, balance, sheets
    if q > sheets or q > balance // 35:
        return False, balance, sheets

    charge = q * 35
    new_balance = balance - charge
    new_sheets = sheets - q
    return True, new_balance, new_sheets


Every rejection returns the unchanged input state. The successful return contains both updated values together, which the caller can adopt when the status is True.

A Python import function accepts a record count only when it is an exact integer from 1 through 200, inclusive. Text values, floating-point values, and booleans must be rejected without conversion. Which acceptance condition implements this requirement?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Match each defensive design term with the description of what it does in a program. Each description fits exactly one term.

Match each term
A.

Stopping with a clear error the moment an invalid state is detected, instead of continuing and corrupting later results

B.

Storing a private duplicate of a caller's mutable object so later changes made by the caller cannot alter data that was already checked

C.

Choosing the outcome that denies access or leaves stored state unchanged when a check cannot be completed

D.

Accepting an input only when it matches an explicitly permitted set of values or patterns and rejecting everything else

E.

A check of a condition the programmer believes is always true, used to expose internal bugs during development rather than to reject user input

F.

An early check at the top of a method that returns or throws when an input is unacceptable, so the main logic runs only on valid data

Assertion

Defensive copy

Allowlist validation

Fail-fast

Guard clause

Fail-safe default

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A telemetry program prepares a message in a buffer with a capacity of 4096 bytes. Every message contains a 160-byte header, and each complete record requires another 72 bytes. There is no other overhead. The program checks capacity before writing any records. What is the largest record count it can accept? Give an exact whole number of records, to zero decimal places. The header occupies part of the same buffer.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice