Reducing Code Entropy

This is a rant: I am tired of seeing virtual methods implemented in child classes that, at some point or another, call the method of the same name in the base class. For me this is a sign of poor architecture. A bad, bad smell in code.

Let’s say that you have a base class, called, well, BaseClass (the examples are in C++, but you can take this idea to any other OO language):

[source:c]

class BaseClass { public: // constructor, destructor, copy // constructor, assignment operator…

virtual void doSomething();

}

void BaseClass::doSomething() { // provide some basic behavior here, // and a comment that says something like:

// IMPORTANT NOTE to implementors of subclasses:
// this method should always be called before your code!

}

[/source]

And then you derive a class from this base class, called, well, DerivedClass:

[source:c]

class DerivedClass : public BaseClass { public: // constructor, destructor, copy // constructor, assignment operator…

virtual void doSomething();

}

void DerivedClass::doSomething() { BaseClass::doSomething(); // WTF???

// do something else...

}

[/source]

As stupid as it might sound, this code is hard to understand, debug and maintain, because it includes an unneeded dependency from the child to the base class – that is, another one, besides the fact that one derives from the other!

Continue reading