Re: Getters / Setters Update
Immortal Nephi <Immortal_Nephi@hotmail.com> wrote:
We discussed proxy class with getters / setters in earlier posts.
You said design is flawed if getters / setters are defined in public.
In another words, my answer is no and design is not flawed.
That depends on the class. The term "class" in C++ means many different
things depending on the situation, and whether or not getters and
setters are appropriate depends on what the class in question is for.
For example:
Class as data bucket. These sorts of classes generally have no
intra-member-variable invariants. For these sorts of classes,
getters/setters are a waste of time and resources. An example of such a
class would be std::pair.
Class as namespace. Classes of this sort are characterized by having
several types defined within them and rarely have member-variables. An
example of such a class would be std::unary_function.
Class as server. These classes generally perform specific tasks at the
behest of their client. They are characterized by a plethora of
member-functions that can only be called when the object is in a
specific state and their functions change the state of the object in
very specific ways. They also often have public invariants. For these
classes, getters and setters are very important. An example would be
std::vector.
Class as object. These sorts of classes usually encapsulate some sort of
state machine, they have maximum flexibility in how to handle their
internal data. These kinds of classes generally don't have any setters
at all (i.e., there are few, if any, functions that have stated
post-conditions that the caller can rely on.) For these kinds of
classes, setters are generally a bad idea, and getters are primarily in
the class to facilitate testing only. I don't know of any examples of
this sort of class in the standard library, but they are quite common in
GUI interface libraries.
You can, of course, have classes that are some mix of two or more of the
above arch-types, but in those cases it is likely that you are trying to
do too much with the class in question and should probably break it up.
Lastly, there may be other arch-types not listed above. These are simply
the ones that came to me in the corse of writing this message.