<Al************ @gmail.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
I have a design type of quesiton.
What is the advantages of using accessor (a getter/setter method)
instead of making
the attribute 'public'?
If a class has public accessor (a getter/setter method) for its
attribute, why not just make the attribute 'public'? It requires less
code/typing. Or is there something I am missing?
Thank you.
If the setting of an attribute of an object causes a side effect, then the
setter method can
incorporate that side effect automatically. For instance, when I set the
color to red of a
"widget", I expect the widget to draw itself in red. Therefore we want to
NOT expose the
raw attributes to the user, but force him to use the setter method to
modify. Consequently,
we also need "getter" to access the internal values of attributes. Setters
can also check for
validity of the value, for instance if the attribute is an integer between
10 and 20, then if you
don't have a setter interface, some pinhead could set the value to -13.
It might be argued that if the attributes have no side effects, then it is
ok to access the attributes
directly. In this situation, objects owning these attributes are not very
interesting as they don't
have much behavior, so it is probably ok to expose their values public ( as
in the C-struct ).
( again, if you want to check the integrity of your data, then don't let
your clients change it
in an uncontrolled way).
Attributes may be be associated with an object, but may not have any
physical representation
on the object, for instance they may be calculated from other data or be
represented on another
object. For example, Volume of a box could be calculated from the box's
sides, but it would not
be good practice to store the value in addition to the sides. Similarly, if
you had a class "boxes"
which contained a number of separate boxes and volume being the volume of
the total of all
the boxes volumes, then this value could be computed on the fly when needed.
Hope that helps.
dave