An accessor method is a class member function that reads object state without defining the operation that changes it. A common mistake is adding a trivial accessor for every private variable. That practice can expose implementation details, burden clients with class knowledge, and weaken the class invariant. section 8.2
Treat accessors as deliberate parts of a class interface:
- Prefer a computing accessor when a value can be derived from existing state; storing and exposing a redundant value increases implementation surface. section 8.2
- Keep state private and control changes through class operations so clients and derived classes cannot bypass invariant checks. section 8.4
- Reduce the number of methods that directly access instance variables; implement other operations through the smallest useful accessor basis. section 9.12
- Do not assume that a private variable plus a trivial getter and setter provides meaningful encapsulation; clients may still depend on representation details. section 8.2
Replace a stored computed value
A Circle that stores both radius and area makes area a redundant implementation detail. A safer interface stores only radius and computes area when requested: `double getArea() const { return radius * radius * PI; }`. This keeps the result synchronized automatically and avoids exposing how it is represented. section 8.2
Listing 8.2 A class with a computing accessor
class Circle {
private:
const static double PI;
double radius;
public:
Circle() : radius(1) {}
Circle(double radius) : radius(radius) {}
double getArea() const { return radius*radius*PI; } #1
};
const double Circle::PI = 3.1415927;
Compare a computing accessor with the version that stores area and exposes trivial getters. section 8.2
Accessors can still form a useful boundary when they are the limited basis for operations such as formatting. In legacy code, improve the boundary incrementally: identify methods touching state, preserve required accessors, and test changes rather than redesigning everything at once. section 9.12












