Re: [Dev-C++] public/private data decision
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Daniel K. O. <dan...@ya...> - 2004-04-13 09:59:00
|
OROSZI Balázs wrote: > It states that use public data ONLY if the whole thing is a data class > (a struct). But what if there ARE a few methods present for the class, > but mostly, it contains data? I tend to agree with Sroustrup: From http://www.artima.com/intv/goldilocks3.html > *Bjarne Stroustrup*: My rule of thumb is that you should have a real > class with an interface and a hidden representation if and only if you > can consider an invariant for the class. > What should count as an invariant? Suppose I have some class, which > stores a file-path internally. The follow up of the interview: > *Bill Venners*: What do you mean by invariant? > > *Bjarne Stroustrup*: What is it that makes the object a valid object? > An invariant allows you to say when the object's representation is > good and when it isn't. Take a |vector| as a very simple example. A > |vector| knows that it has n elements. It has a pointer to n elements. > The invariant is exactly that: the pointer points to something, and > that something can hold n elements. If it holds n+1 or n-1 elements, > that's a bug. If that pointer is zero, it's a bug, because it doesn't > point to anything. That means it's a violation of an invariant. So you > have to be able to state which objects make sense. Which are good and > which are bad. And you can write the interfaces so that they maintain > that invariant. That's one way of keeping track that your member > functions are reasonable. It's also a way of keeping track of which > operations need to be member functions. Operations that don't need to > mess with the representation are better done outside the class. So > that you get a clean, small interface that you can understand and > maintain. > Ando this: > *Bill Venners*: The invariant is a relationship between different > pieces of data in the class. > > *Bjarne Stroustrup*: Yes. If every data can have any value, then it > doesn't make much sense to have a class. Take a single data structure > that has a name and an address. Any string is a good name, and any > string is a good address. If that's what it is, it's a structure. Just > call it a |struct|. Don't have anything private. Don't do anything > silly like having a hidden name and address field with |get_name| and > |set_address| and |get_name| and |set_name| functions. Or even worse, > make a virtual base class with virtual |get_name| and |set_name| > functions and so on, and override it with the one and only > representation. That's just elaboration. It's not necessary. > So, (I think) your class is no more than a struct (with all data public), and methods to do stuffs with it. Daniel K. O. |