Re: Public member variables acceptable?
Seungbeom Kim <musiphil@bawi.org> wrote:
Daniel T. wrote:
Seungbeom Kim <musiphil@bawi.org> wrote:
Francis Glassborow wrote:
francis_r wrote:
On what principles would the decision to declare a member
public be based?
[...] In general start by making data private until you have an
overwhelming design imperative to make them public.
Would there ever be any overwhelming design imperative to change
already-private data members into public? I doubt it...
Good point. There are design imperatives that would cause you to want to
make a public data member private, but likely no imperative to make
private ones public. So, why make them public in the first place?
Because it may be just what you need, and further encapsulation of
things that don't need one is meaningless.
You mean it may be what you can get away with... For now...
since you already paid the costs by writing the accessor functions
and using them (e.g. p.set_x(p.get_x() + delta)) which is more
verbose than the public data member version (e.g. p.x += delta).
Reverting to the latter would make the code look simpler and
cleaner...
As if those were your only two choices. "tell, don't ask" implies that
the member-function version should be more like p.changeXBy( delta ).
Personally, I don't see p.x += delta as simpler or cleaner than that.
That's a possible case. But there could be also something like this:
// set x and y in some hidden manner, given the old position
void set_position(int& x, int& y);
// with public data members:
set_position(p.x, p.y);
// with private data members and public accessor functions:
int x = p.get_x(), y = p.get_y();
set_position(x, y);
p.set_x_y(x, y);
And if private member-variables make such poor interfaces harder to
write, that's a good thing. Your 'set_position' should be something more
like:
Point change( const Point& p );
p = change( p );
You have the Point abstraction, now all you have to do is start using it.
Using the data members directly is no more complicated than using
the accessor functions.
If that were true, then there would be no reason to ever make data
members private. It isn't true though.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]