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
