OO conventions

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Feb 2 06:08:33 EST 2006


On Wed, 01 Feb 2006 23:40:37 +0100, Daniel Nogradi wrote:

> I'm relatively new to object oriented programming, so get confused
> about its usage once in a while. Suppose there is a class Image that
> has a number of methods, rotate, open, verify, read, close, etc. Then
> to use this class my natural guess would be to have something like
> 
> image = Image( )

Now you have an "image" object. What is it?

Answer: it isn't an image at all, not in the plain English sense. (Or if
it is, it is an arbitrary "default image" picked by the class designer.)

> image.read( "myfile.jpg" )

And now, at long last, the image object actually is an image. So why make
this a two step process? Whatever the Image() initialization does, why
can't it be done automatically when you read the file?

[snip]

> Perhaps the real Image class of PIL doesn't have these methods exactly,
> but doesn't matter, my point is the way it works. Is it normal that
> instead of first creating an instance of a class, it starts right away
> with one its methods? I of course understand that the PIL people simply
> made a choice that their module works this way, period, but I'm just
> wondering if it wouldn't have been more "logical" to do it along the way
> of my first example.

It seems to me that the choice depends on the data you are handling, plus
of course the class designer's choice. (Dare I say it, whim.)

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.

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

then you are just doing pointless make-work to fit a convention that
doesn't make sense for your class. 



-- 
Steven.




More information about the Python-list mailing list