(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
There are several levels to "Getting" and "Setting"
So Get/Set can be ascribed a useful meaning, and be part of a larger, consistent naming strategy.
I'll go ahead and mention this should be a community wiki question.
When I started learning C++ I looked for style guides, and Google's was good for some points:
rate
).setRate
).Personally, I think getters and setters found in pairs are a code smell carried over from "visual" languages and their "properties". In a "good" class, the data members are writeonly or readonly but not read/write.
I think the most common cause of getters and setters is not carrying the object model deep enough. In your example, why is total being passed the period and the rate? Aren't they members of the class? So you should only be setting the period and the rate and you should only be getting a total.
There are probably exceptions but I just hate looking at a class and finding "getX/setX, getY/setY, etc. etc." It just seems there wasn't enough thought put into how the class SHOULD be used and rather the author made the class EASY to get at the data so he wouldn't have to consider how the class should be used.
Naturally I am correct.
I prefer to avoid the get and set labels, the information is not needed for the compiler to do it's job for most of these simple properties.
you can have issues:
class Stuff {
void widget( int something ); // 'special' setter
const Widget& widget( int somethingelse ) const; // getter
}
Stuff a;
a.widget(1); // compiler won't know which widget you mean, not enough info
A few years ago, I would have agreed completely. More recently, a doubt began to make its way, because that makes taking the address of a getter or setter ambiguous. With tools like tr1::bind, this is really annoying.
For example:
struct A
{
void Foo(int);
int Foo()const;
};
std::vector<A> v = ....;
std::vector<int> foos;
// Extract Foo
std::transform(
v.begin(), v.end(),
std::back_inserter(foos),
//Ambiguous
// std::tr1::bind(&A::Foo)
//must write this instead. Yuck!
std::tr1::bind(static_cast<int(Foo::*)()>(&A::Foo));
);
Leaving aside the question of should you have them at all ;-)
While Ed's comment is true, I do prefer actual properties over the setter/getter antipattern. When 1/3rd of the methods in your domain graph are dummy methods that have been generated by eclipse, there's something wrong.
Without first class properties, however, I believe the antipattern makes the most sense.
Furthermore, it makes code completion easier.
obj.set (control shift space)
for setters
obj.get (control shift space)
for getters