Consider the following class:
class MyClass1
{
public:
double x() const {return _x;} // getter
double y() const {return _y;} // getter
double z() const {return _x*_y;} // getter
void x(const double var) {_x = var;} // setter
void y(const double var) {_y = var;} // setter
void z(const double var) {_x = var; _y = 1;} // setter
protected:
double _x;
double _y;
};
As the actual contents of MyClass1
is an implementation detail, the getters and setters provide a unified way to get and set the class contents even if they are interdependant (here _z
does not exists internally but for the user, z
is a variable like x
and y
).
Now to avoid to have to write getter/setter for x
and y
, one can use a wrapper like this:
template <typename Type>
class Wrapper
{
public:
constexpr Wrapper(const Type& value) {_value = value;}
constexpr Type& operator()() {return _value;}
constexpr const Type& operator()() const {return _value;}
constexpr void operator()(const Type& value) {_value = value;}
protected:
_value;
};
And now the original class becomes:
class MyClass2
{
public:
Wrapper<double> x;
Wrapper<double> y;
double z() const {return x*y;} // getter
void z(const double var) {x = var; y = 1;} // setter
};
Is it a dangerous practice or a good solution to avoid to have to write getters/setters ?
Note : Here MyClass1
and MyClass2
are just examples. My question is very "general" : is it dangerous to replace getters/setters of classes by the proposed Wrapper
when the getter/setter just return/set an internal value.