Accessors in Python (getters and setters)

Ben C spamspam at spam.eggs
Sat Jul 15 18:46:16 EDT 2006


On 2006-07-15, Gerhard Fiedler <gelists at gmail.com> wrote:
> On 2006-07-15 06:55:14, mystilleef wrote:
>
>> In very well designed systems, the state of an object should only be
>> changed by the object. 
>
> IMO that's not quite true. Ultimately, the state always gets changed by
> something else (user interaction, physical events); very few objects are
> completely self-contained in their behavior.
>
> In most systems (and you possibly have written some of them) are objects
> whose state gets changed by other objects -- possibly through the
> intermediation of setter methods that do nothing else but set the state.
> There's no conceptual difference between directly setting the state or
> calling a setter function that does nothing else but directly setting the
> state -- except for one unnecessary level of indirection in the latter.

The conceptual difference is that a function call is more like an "event",
a variable is more like a "process".

An object that provides a setter is a process that is prepared to engage
in this "set event". An object that exposes a variable is a process that
interacts with this variable which the user is also invited to interact
with concurrently.

So with a setter in the API, conceptually, there are two processes
sharing the set event: the object itself, and the process that's calling
the setter. With an exposed variable, there are three: the object, the
variable in between, and the calling process.

Restricting yourself to setters and getters is a bit like saying we
build a machine that only has touch-keys and lights on the outside.
Shared variables are more like a machine with levers and dials you set,
and bits that pop up, like the numbers on mechanical cash-registers.
They have "state" on the outside, not just on the inside. Such designs
can be less tolerant of unsympathetic input-- think how easy it is to
jam up an old-fashioned typewriter if you just press a few keys at the
same time.

There isn't any practical difference, as you say, if all the setter does
is set. But it might easily do a few other subtle things, in particular
wait for a good moment to actually effect the change.



More information about the Python-list mailing list