git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Object-oriented philosophy


"Michael F. Stemper" <michael.stemper at gmail.com>:

> Since the three classes all had common methods (by design), I
> thought that maybe refactoring these three classes to inherit from
> a parent class would be beneficial. I went ahead and did so.
> (Outlines of before and after are at the end of the post.)
>
> Net net is that the only thing that ended up being common was the
> __init__ methods. Two of the classes have identical __init__
> methods; the third has a superset of that method. The other methods
> all have completely different implementations. This isn't due to
> poor coding, but due to the fact that what these model have
> different physical characteristics.
>
> [...]
>
> Is there really any benefit to this change? Yes, I've eliminated
> some (a few lines per class) duplicate code. On the other hand,
> I've added the parent class and the (probably small, but not
> non-existent) overhead of invoking super().
>
> How does one judge when it's worthwhile to do this and when it's
> not? What criteria would somebody seasoned in OO and python use
> to say "good idea" vs "don't waste your time"?

Ultimately, a seasoned OO programmer might prefer one structure in the
morning and another structure in the afternoon.

Python's ducktyping makes it possible to develop classes to an interface
that is not spelled out as a base class. My opinion is that you should
not define base classes only to show pedigree as you would need to in,
say, Java.

Then, is it worthwhile to define a base class just to avoid typing the
same constructor twice? That's a matter of opinion. You can go either
way. Just understand that the base class doesn't serve a philosophical
role but is simply an implementation utility. Be prepared to refactor
the code and get rid of the base class the moment the commonality
disappears.

On the other hand, why is it that the two constructors happen to
coincide? Is it an indication that the two classes have something deeper
in common that the third one doesn't? If it is not a coincidence, go
ahead and give the base class a name that expresses the commonality.

Don't be afraid of "wasting your time" or worry too much about whether
something is a "good idea." Be prepared to massage the code over time as
your understanding and tastes evolve.


Marko