I find, when coding C++ code, that I spend a lot of time writing accessor boiler plate code, such as:
class A
{
int x;
public:
auto x();
void set_x(decltype(x));
};
The whole idea of implementing accessors revolves around being able to intercept read and write accesses to them. I stumbled on this library (I'm not the author). It really makes me wonder, if, to avoid having to write boilerplate code, one could/should just write something like:
class A
{
public:
property<int> x;
A() {
x.setter([this](int){ /* setter code */ });
}
};
My question is: What techniques are available to avoid having to write a lot of boilerplate code for getters and setters?
There is some discussion here and there about whether getters and setters are evil in general.
So, my strategy for avoiding boilerplate code: Try to avoid getters and setters. When in need of some pure data class I declare the (few) fields public. But in these cases I try to avoid giving them any other logic, I try to keep these classes as little as possible.
Also, read about tell-don't-ask, e.g. from Martin Fowler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With