(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 s
Another issue no one else has mentioned is the case of function overloading. Take this (contrived and incomplete) example:
class Employee {
virtual int salary() { return salary_; }
virtual void salary(int newSalary) { salary_ = newSalary; }
};
class Contractor : public Employee {
virtual void salary(int newSalary) {
validateSalaryCap(newSalary);
Employee::salary(newSalary);
}
using Employee::salary; // Most developers will forget this
};
Without that using
clause, users of Contractor
cannot query the salary because of the overload. I recently added -Woverloaded-virtual
to the warning set of a project I work on, and lo and behold, this showed up all over the place.
If your getter is simply rate()
, your compiler would complain that its a redefinition of your other rate
symbol, provided you gave your field a good meaningful name like that. In that case you need to do something silly like name your member _rate
or some other similar approach. I personally hate seeing/typing those underscores, so tend to go with the getRate()
approach.
This is obviously subjective and this just happens to be my personal preference.
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?
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.
How about int rate();
and void setRate(int value);
? This has the virtue of not having two functions of the same name doing different things, and still allows period() * rate()
.
Being concise is important, but not at the cost of being incomplete or misleading. For that reason, I prefer GetFoo() and SetFoo() to Foo() and Foo(int foo).