: MIDRANGE dot COM Mailing List Archive

RE: Java Style Question


AddThis Feed Button


> From: Larry Loen
>
> The question is a practical one -- are you likely to have MyVar be the
> subject of some form of inheritance?  Will the apparent simple assignment
> becomes something else in the child?  In that case, getters and
> setters are mandetory.

This is a crucial observation, and one that is not easy to fully grasp.  The
idea is simple: will you at some point need to override how this field is
accessed?  It is not always immediately obvious whether this will be the
case.

Let's take a simple example.  On a web page, you want to output a colored
string.  You specify two things: the string to display and the color.  You
call your class ColoredString.  The string and color are set when the object
is created.  Your formatter access those two values to create the
appropriate HTML.  It seems safe enough to directly access the color value,
doesn't it?

Well, what if some day you want to extend that class so that the color
depends on, oh, I don't know, a flag in the output buffer perhaps?  Dare I
call it an INDICATOR?  <smile>  In any event, the code that formatted the
output and directly accessed the color variable would start to get a little
more kludgy.  In fact, it would have to actually set the internal variable
prior to calling the formatter, and that's not necessarily a good idea.  At
the very least you have to add a setter method, and once you've done that,
it's pretty easy to add a getter method and the whole problem goes away.

I don't want to get into a long diatribe here about setters and getters as
opposed to internal variables.  The purest way is to always use getters and
setters, thereby allowing subclasses the ability to override the behavior of
the attribute.  I have been bitten more than once by class variables being
accessed directly.





Return to Archive home page | Return to MIDRANGE.COM home page

This mailing list archive is Copyright 1997-2007 by MIDRANGE dot COM and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available here. If you have questions about this, please contact

.

counter