Conventions for accessor methods (getters and setters) in C++
Solution 1:
From my perspective as sitting with 4 million lines of C++ code (and that's just one project) from a maintenance perspective I would say:
It's ok to not use getters/setters if members are immutable (i.e.
const
) or simple with no dependencies (like a point class with members X and Y).If member is
private
only it's also ok to skip getters/setters. I also count members of internal pimpl-classes asprivate
if the .cpp unit is smallish.If member is
public
orprotected
(protected
is just as bad aspublic
) and non-const
, non-simple or has dependencies then use getters/setters.
As a maintenance guy my main reason for wanting to have getters/setters is because then I have a place to put break points / logging / something else.
I prefer the style of alternative 2. as that's more searchable (a key component in writing maintainable code).
Solution 2:
2) is the best IMO, because it makes your intentions clearest. set_amount(10)
is more meaningful than amount(10)
, and as a nice side effect allows a member named amount
.
Public variables is usually a bad idea, because there's no encapsulation. Suppose you need to update a cache or refresh a window when a variable is updated? Too bad if your variables are public. If you have a set method, you can add it there.
Solution 3:
-
I never use this style. Because it can limit the future of your class design and explicit geters or setters are just as efficient with a good compilers.
Of course, in reality inline explicit getters or setters create just as much underlying dependency on the class implementation. THey just reduce semantic dependency. You still have to recompile everything if you change them.
This is my default style when I use accessor methods.
This style seems too 'clever' to me. I do use it on rare occasions, but only in cases where I really want the accessor to feel as much as possible like a variable.
I do think there is a case for simple bags of variables with possibly a constructor to make sure they're all initialized to something sane. When I do this, I simply make it a struct
and leave it all public.
Solution 4:
That is a good style if we just want to represent
pure
data.I don't like it :) because
get_/set_
is really unnecessary when we can overload them in C++.STL uses this style, such as
std::streamString::str
andstd::ios_base::flags
, except when it should be avoided! when? When method's name conflicts with other type's name, thenget_/set_
style is used, such asstd::string::get_allocator
because ofstd::allocator
.