[Exceptional C++ Style] Item 17 - Encapsulation

Jon Jagger jon at jaggersoft.com
Mon Dec 20 17:32:46 EST 2004


Timothy Wright wrote:

>>To bring this back to the original point - should classes be allowed expose
>>member data if that data is const? I still say no. The function of the class
>>should be made apparent via its interface, and even if all a class did was
>>provide access to some const data, it is still advantageous to wrap this in
>>an interface. If there was just a single reason to do this, surely that is
>>all it should take to convince you? 
>>    
>>
>
>I concur.  I am always changing my code refactoring due to changing
>needs.  I am never sure of anything.  Code I write this week might
>need to be changed next week.  If I make members public even if they
>are const, it ties my hands and requires more changes to more code if
>and when they come.  If the values are accessed thru get/set I have
>least one indirection that could help me.
>
>I have a hard time knowing if my design decisions today might haunt me
>tomorrow (and usually they do) so I take as much insurance as possible
>with encapsulation.  At least more now that I have done in the past.
>
>  
>
Of course. The only thing we know for sure is that change will happen. 
The only real question is where do you draw the line. If you want 
absolute protection from change you could put everything behind a var 
arg method called do_it. But we don't do that. Instead we opt for a more 
strongly typed expression of the problem/solution. We never take as much 
insurance as possible. We always adopt, to some degree, a style.

When I first wrote the grammar_definition class I considered using 
getter methods. But I choose not to. In all the time since then I have 
not once had cause to revisit that decision. If I had the getters would 
no doubt now be in place. I'm not saying there haven't been changes - 
there's been lots. Languages change (eg Java 1.4 got assert) and I have 
often needed to change the description of an existing non-terminal and 
to introduce new non-terminals, regenerate, write more tests, etc. The 
grammars change, but the nature of what it means to be a grammar does not.

Cheers
Jon







More information about the Effective-cpp mailing list