[Exceptional C++ Style] Item 17 - Encapsulation

solosnake . solosnake at hotmail.com
Mon Dec 20 08:11:35 EST 2004


>From: Jon Jagger <jon at jaggersoft.com>
> >compared to what? here's a grammar_definition object...
>
>grammar_definition js;
>
> >and an example of using it (to get at one of the const data members) 
>is...
>
>const non_terminal_definition & x = js.if_statement;
>
> >compared to getting at it via an accessor...
>
>const non_terminal_definition & x = js.if_statement();
>
> >how is the dependency any different?
>

Hello

Are we debating as to which of these two following classes is the best to 
use? Ignoring your specific implementation, which may as a special case 
justify the design decisions you took, I am arguing that there is no 
advantage to public (but const) member data, and that there are real 
disadvantages.

// Case 1 : Encapsulated data.
class Case1
{
public:
    const SomeData& GetSomeData()const;
private:
    const someData_;
};

// this could also be inlined instead.
const SomeData& Case1::GetSomeData()const
{
    return someData_;
}

// Case 2 : public const data.
class Case2
{
public:
    const someData_;
};

Is there really an argument for case 2? Case 1 allows all the functionality 
required for any usage of case 2, but is safer, conforms to (an assumed) 
coding style of functional access to data, and most importantly, is future 
proof. If at some later date we need decide that in fact the 'SomeData' 
object is in fact going to reside somewhere else, or any other reason why 
the member data may change, users of Case 1 don't care - they are 
unaffected. For no strong reason, case 2 has created a dependency on its 
internals.

Cheers,

Daire Stockdale





More information about the Effective-cpp mailing list