(Leaving aside the question of should you have them at all.)
I have always preferred to just use function overloading to give you the same name for both getter and setters.
int rate() { return _rate; }
void rate(int value) { _rate = value; }
// instead of
int getRate() { return _rate; }
void setRate(int value) { _rate = value; }
// mainly because it allows me to write the much cleaner
total( period() * rate() );
// instead of
setTotal( getPeriod() * getRate() );
Naturally I am correct, but i wondered if the library writers had any good reason ?
I would prefer the get/set versions because it is more clear as to what is going on. If I saw rate() and rate(10), how do I know that rate(10) isn't simply using 10 in the calculation to return the rate? I don't, so now I have to start searching to figure out what is going on. A single function name should do one thing, not two opposing things.
Also, as others have pointed out, some prefer to omit the 'get' and leave the 'set', i.e.,
int Rate( );
void SetRate( int value );
That convention is pretty clear as well, I wouldn't have any problem reading that.
I have always preferred to omit the 'get' on my getters, as you do, with rate()
instead of getRate()
. But overloading for the setter does not seem like a very good idea to me, since the name rate
doesn't convey that the object is being mutated. Consider:
total(period() * rate()); // awesome, very clear
rate(20); // Looks like it computes a rate, using '20'...but for what? And why ignore the return value?
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