× The internal search function is temporarily non-functional. The current search engine is no longer viable and we are researching alternatives.
As a stop gap measure, we are using Google's custom search engine service.
If you know of an easy to use, open source, search engine ... please contact support@midrange.com.



> 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.



As an Amazon Associate we earn from qualifying purchases.

This thread ...

Replies:

Follow On AppleNews
Return to Archive home page | Return to MIDRANGE.COM home page

This mailing list archive is Copyright 1997-2024 by midrange.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 on our policy page. If you have questions about this, please contact [javascript protected email address].

Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.