liveBook · Manning

Code divergence

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

The condition in which duplicated implementations become inconsistent because changes are applied to one copy but not another.

Code divergence occurs when duplicated implementations are changed differently. Multiple constructors can calculate related state in separate places, so one correction may leave another behavior wrong. Establishing a minimal basis of essential, non-overlapping functions reduces duplicated knowledge, maintenance effort, and cognitive load. section 7.5

Listing 7.5 Duplicated knowledge in a class
class Cylinder {
private:
    double radius;
    double height;
    double area;
    double volume;
public:
    const double PI = 3.1415927;
    Cylinder() {
        radius = 1;
        height = 1;
        area = PI;
        volume = PI;
    }
    Cylinder(double h) {
        radius = 1;
        height = h;
        area = PI;
        volume = PI * h;
    }
    Cylinder(double r, double h) {
        radius = r;
        height = h;
        area = PI * r * r;                               #1
        volume = PI * r * r * h;                         #2
    }
    double getBaseArea() const { return area; }
    double getVolume() const { return volume; }
};

The Cylinder constructors duplicate area and volume calculations; later changes must be applied consistently across each implementation. section 7.5

A safer design centralizes initialization and derives related operations from a small basis. The corrected Cylinder uses init for shared constructor setup, calculates base area once, and derives volume from that result. The same reasoning applies to methods and standalone functions: implement essential behavior once, then define related behavior in terms of it. section 7.5

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

How deep it goes
Explains basis functions through constructor and arithmetic examples, then demonstrates centralized initialization and derived operations.
Examples
Uses a Cylinder with three constructors, duplicated geometry calculations, and a refactored init-based implementation.
What it assumes
Assumes familiarity with constructors and functions while teaching the basis-function idea through arithmetic and geometry examples.
What you can do after
Apply a minimal-function approach to centralize shared behavior and reduce inconsistent implementations.
How it connects
Connects code divergence with DRY, class invariants, constructors, methods, and standalone functions.

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.