liveBook · Manning

Immutable collection

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

Immutable data is data whose value cannot be changed after it has been created.

Mistake: treating a value object as mutable state. Immutable data keeps its value fixed after construction. For a Rational number, mutators can break the class invariant and make every client reason about invalid intermediate states. Remove setters when the problem does not require mutation. section 7.4

Make Rational values stable

A naïve Rational class exposes setNumerator and setDenominator, uses floating-point members, and permits a zero denominator. A safer interface stores integer components, validates the denominator during construction, reduces the value internally, and returns new Rational objects from addition and multiplication rather than altering an operand. section 7.4

When reviewing a value-like class:

  • Ask whether the represented value can ever change. section 7.4
  • Hide helpers such as gcd and reduce when clients do not need them. section 7.4
  • Name operations clearly and make their result behavior intuitive. section 7.4

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

How deep it goes
Explains mutation decisions through Rational design, then stops short of a general immutability framework.
Examples
Uses a Rational class with setters, denominator validation, reduction, addition, and multiplication.
What you can do after
Evaluate value-like class interfaces and replace unnecessary mutation with construction-time validation and result-producing operations.
How it connects
Connects immutability with class invariants, encapsulation, accessors, mutators, and operator overloading.

Also explained in

Compare how 24 books explain immutable collection →

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.