liveBook · Manning

Trivial mutator

As explained in 100 C++ Mistakes and How to Avoid Them

A trivial mutator is a state-changing member function that directly assigns an input value to an instance variable without enforcing relevant constraints.

A trivial mutator directly assigns an input to an instance variable. In legacy C++, this can accept invalid values, break the class invariant, and duplicate validation rules from the constructor. section 8.3

The pattern creates three practical problems:

  • Unvalidated input lets clients place improper values inside an object. section 8.3
  • Unnecessary mutability makes classes harder to read and can undermine correctness. section 8.3
  • Repeated constructor and mutator checks can diverge as the code changes. section 8.3

A safer mutator validates candidate values before assignment. Centralizing that check in validateRadius lets both construction and modification enforce one class invariant without duplicating its rules.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains invalidation, unnecessary mutability, and duplicated validation, then demonstrates centralized validation in C++.
Examples
Uses a Circle radius setter, negative-radius input, duplicated checks, and a shared validation helper.
What it assumes
Assumes basic classes, constructors, instance variables, and member functions while defining invariant maintenance through examples.
What you can do after
Diagnose/debug with it by locating unrestricted assignments and consolidating invariant checks before state changes.
How it connects
Connects mutators with class invariants, constructors, validation, instance variables, and legacy code maintenance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.