Accessor Methods (Was: Re: An evangelist's handbook?)

Alex Martelli aleax at aleax.it
Wed Nov 13 11:06:05 EST 2002


Hung Jung Lu wrote:

> Alex Martelli <aleax at aleax.it> wrote in message
> news:<owWy9.11842$XO.493367 at news2.tin.it>...
>> >    What is the benefit of "public by default"?
>> 
>> Minimizing boilerplate.  90% of exposed properties in languages and
>> object models which don't support that lead to a lot of boilerplate:
   ...
> I agree with accessor methods being boilerplate in Python. But in C++,
> under some circumstances, it's a real necessity.

That's exactly the same thing I'm saying: C++ is an example of
a language that doesn't support 'properties', which is one reason
(out of many) which causes C++ code to need a lot of boilerplate.

Note that the fact that the language makes it necessary doesn't
mean such repetitious, performs-no-real-function code ISN'T
boilerplate; "boilerplate" and "real necessity" aren't antonyms.


> C++ has virtual methods, but no virtual data members.
> 
> And, that to me, is the main reason why C++ needs accessor methods.

It's ONE reason, yes -- subclasses cannot "override data" the way
they can in Python.  However, there are other reasons: in C++, if
you expose an instance attribute X to clients, then client code
written to access blahblah.X needs X to be and remain a data
attribute forevermore -- the fact that X is data has become part
of your class's interface.  Therefore, to keep the flexibility to
change your class in the future, so that X can perhaps be computed
on the fly rather than stored, you DARE NOT expose X as an
attribute on a public interface.

Python's ability to "override data" is amazingly powerful (and
plays incredibly well with the "Template Method" Design Pattern,
too).  But you don't need to go that far to remove the need for
accessors: languages such as Delphi (Object Pascal), Eiffel, and
the C++ dialects/extensions peddled by Borland and Microsoft, all
manage to allow blahblah.X to compile to EITHER a data access OR
a call on some accessor method of blahblah as appropriate.


Alex




More information about the Python-list mailing list