On 23 Feb 2004 22:52:49 -0800,
sp**********@ya hoo.com (sb) wrote:
I'm sure some people feel very productive when they write
private:
t m_foo;
public:
const t& foo() const { return m_foo; }
t& foo() { return m_foo; }
and then go on to replicate most of the contents of std::vector.
Wheeee! Accessors! Const-correct ones! Wheee! 300 lines of code in one
hour. The manager must be realy proud of me! Thanks. I think I'll
pass.
Actually those 300 lines of code can save you *lots* of time. If
m_foo is public, what will happen when you will have to change
your class's implementation? Imagine this:
class T_Wrapper {
// no const-correctness in this class because it isn't
// what we're talking about
public:
T foo;
void print() {
string s = makeStringRepre sentation();
cout << s;
}
string makeStringRepre sentation() {
// lots of time-consuming processing here
}
};
And in the client code:
void f(T_Wrapper& tw) {
tw.foo = someValue;
tw.print();
}
One day you decide to optimize makeStringRepre sentation():
class T_Wrapper {
public:
T foo;
string cachedStringRep ;
bool cacheIsUpToDate ;
void print() {
if ( ! cacheIsUpToDate ) {
cachedStringRep = makeStringRepre sentation();
cacheIsUpToDate = true;
}
cout << cachedStringRep ;
}
string makeStringRepre sentation() {
// same as above
}
void setFoo(T newFoo) {
foo = newFoo;
cacheIsUpToDate = false; // let's not forget this
}
};
Well, now f() is broken, because it changes foo without setting
cacheIsUpToDate to false. And so is all your client code. You
have to rewrite (or at least check) *everything*.
I think data members should be private even if they are part of
the interface. Unless, of course, you have some good reason to
do otherwise.
And, by the way, const-correctness is useful too...
;-)
--
Andre Heinen
My address is "a dot heinen at europeanlink dot com"