OO conventions

Nicola Musatti nicola.musatti at gmail.com
Fri Feb 3 08:05:20 EST 2006


Steven D'Aprano wrote:
[...]
> If a class has a natural, obvious default state (e.g. a mutable string
> class might start off empty, a mutable int class might start off as zero,
> a binary tree might start off as an empty node with no children) then it
> makes sense to initialise the class, then add your data.
>
> But if the class has no natural default state, then it makes no sense to
> create an "empty object" with no data, a "non-image image" so to speak.

I don't think this is all there is to it. Even though a class such as
Image might not have a sensible default, initial state it still might
not be reasonable to burden it with the ability to collect the
information needed to reach such an initial state. To put it it another
way: a car is a car, it isn't a car factory.

> In other words, if you find yourself writing methods like this:
>
> class Klass:
>     def foo(self):
>         if self.data is None:
>             raise KlassError("Can't foo an uninitialized Klass object.")
>         else:
>             # do something

Factory functions (or classes) are there to solve this problem and
still allow a clean separation of concerns. Although instances of Klass
are created uninitialized, they only live in this state within their
factory and only reach trhe outside world only when they are in a
usable state.

Cheers,
Nicola Musatti




More information about the Python-list mailing list