Courses / Computer Science I
Programming II

Defensive Programming and Debugging

Computer Science I 184 words Free to read

Programming for a Hostile World

Real programs face bad inputs and imperfect environments. Defensive programming anticipates these problems so code behaves safely instead of crashing or outputting garbage.

TermDefinition
Input validationChecking that inputs meet assumptions before use.
AssertionsStatements of a condition that must be true (assert n0assert\ n \ge 0).
Failing fastDetecting errors close to their source to stop propagation.

Rejecting bad input at the boundary with a clear error prevents silent state corruption deep inside the program.

A value is stopped at the door, not chased down after it gets in

Contracts and Pitfalls

Functions require clear preconditions (what inputs are needed) and postconditions (what outputs are guaranteed). Handle errors explicitly via exceptions rather than ignoring them.

Contract AspectPurpose
PreconditionsDocument and enforce valid inputs.
PostconditionsGuarantee correct output state.
Common pitfall: Trusting that inputs will always be valid because "no one would ever pass a negative here." Unvalidated assumptions break production code. Validate at boundaries and fail fast.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes

Programming II