Re: public member variable vs. get/set functions
On 09.12.13 23.39, W Karas wrote:
The main purpose of private members is to provide some level of compile time checking for the rules of use of an object that must be followed, in order to keep the object in a valid state.
Given that, a private member variable with (simple, public) get/set functions just seems like pointless code bloat. It provides no additional protection against putting the object in a bad state than having the member variable be public.
It also creates no overhead in an optimized build as long as your
getter/setter is implemented inline.
Some (perhaps Smalltalk fans) argue that it's very rare that simply setting a member variable should properly be part of an objects public interface. Therefore, it's best to follow the rule of thumb that all member variables should be private.
It can also be argued that it is often important, for code maintenance, to be able to quickly identify external changes to a member variable, as opposed to read access to the variable. A counter-argument is that some sort of code browsing tool should be available to prevent the need to bloat the code in order to highlight this distinction.
Eclipse CDT can mostly distinguish between read and write access in the
references view.
In some cases, it could be likely that the get/set function would eventually do more than simple get/set a single member variable. That would be a clear case where keeping the member variable private would be the correct choice. But, as I have seen Dr. Bjarne argue, it's easy to go overboard with future-safety.
If you intend to change the behavior in future versions using
getters/setters might keep source code compatibility.
Your thoughts?
I usually do not use simple getters/setters. But I usually also do not
need public member variables, except for const ones.
Marcel