liveBook · Manning

Defensive programming

As explained in Object-Oriented Software Design in C++

A programming technique that validates inputs and guards against invalid states or programming errors.

Defensive programming guards against programming errors by checking function parameters and preventing invalid objects or states from being created. section 2.3.4

Apply the technique by:

  • Representing permitted value types explicitly with a variant. section 2.3.4
  • Associating each key with its required datatype. section 2.3.4
  • Checking parameter values at runtime before constructing an object. section 2.3.4

Validating book attributes

An Attributes object stores book properties such as YEAR, TITLE, and GENRE. Its constructor verifies that each value matches the key’s required type, rejecting combinations such as a string supplied for YEAR. Searches can then compare valid attribute pairs while treating absent target attributes as don't-care fields. section 2.3.4

How Object-Oriented Software Design in C++ covers it

How deep it goes
Explains runtime parameter checks through a variant-backed map and constructor assertions, while deferring broader checking in short examples.
Examples
Uses typed book attributes, constructor assertions, catalogue searches, and partial queries such as genre and author.
What it assumes
Assumes basic functions and objects while demonstrating variants, maps, enumerations, and runtime assertions in context.
What you can do after
Apply runtime validation to construct only proper objects from parameter values.
How it connects
Connects runtime checks with variant types, enumerations, maps, object validity, 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 Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.