liveBook · Manning

Defensive programming

As explained in Software Design for Python Programmers

Defensive programming is a technique that validates inputs and guards against programming errors to preserve valid program states.

Defensive programming validates inputs and guards against programming errors so objects remain valid. Constructors should create only proper objects from their parameter values. section 2.3.4

Apply the technique by:

  • Checking parameter values at runtime before constructing an object. section 2.3.4
  • Keeping invalid values out of the Attributes object rather than repairing them later. section 2.3.4

Typed book attributes

Attributes.__init__() checks YEAR for int, text fields for str, and categorical fields for the appropriate Enum class. Valid attributes can then support case-insensitive matching and don’t-care search fields.

How Software Design for Python Programmers covers it

How deep it goes
Shows constructor assertions and matching behavior, while noting that broader examples generally omit parameter checks.
Examples
Uses typed book attributes, invalid-value prevention, case-insensitive author matching, and partial catalogue searches.
What it assumes
Assumes familiarity with function parameters and dictionaries while teaching attribute datatypes through explicit checks.
What you can do after
Build valid Python domain objects and diagnose invalid parameter values before they enter the application.
How it connects
Connects input validation with constructors, enumerations, datatype constraints, and attribute matching.

Also explained in

Compare how 2 books explain defensive programming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.