Main Content

Designing a heirarcy of classes - getting inheritance right

Archive - Originally posted on "The Horse's Mouth" - 2009-05-11 04:54:39 - Graham Ellis

You friend Will has written a class to handle management information about articles. It's great as far as it goes, but you want to add extra stuff to it, so you persuade Will to give you a copy. He's a nice guy, he does so ... but then a month later he tells you he's added a lot more code and you're forced to make a lot of changes to your derivative work ... and so is Jane, to whom you had in turn passed a copy of the code. Far, far better to write the code to OO principles, in which you simply write a file that describes the changes and can be automatically applied when you get Will's update. But this requires careful class design.

Here are some of the principles involved ...

From a class of "article", I have specified three derived classes - blog article, web published article and metro article. The blog article in turn is split into published and draft, and the draft is further split into withdrawn and future. In each case of inheritance, the class on which the new class is based is known as the "base class" and the newly created class is known as the "sub class" ... and we call this extending a class. This might sound back to front at first, but when you consider that you extend the code to create a class that will be more specific and have fewer members, it starts to make sense.


A base class of film contains a lot of methods and data .. but we have had to subclass it to "blockbuster" and "cinema" for our "getcost" method ... since you pay per person at the cinema, but per film hired from Blockbuster - a different algorithm demanding a different (but related) class


In order to minimise the amount of code you need, you should put common code as near to the root of the tree as possible. In this specification example, you'll see that I have put "gettext" into the base article class, as it's common over most of the subclasses. I have then added a separate "gettext" method into my draft brog article class, as that works on different principles. This replacement technique is overloading


Where there's no obvious way to overload a class, the addition of an intermediate class in the hierarchy - even if it's an object typel you'll never create - can help you out. In this example, I wanted a "getvet" method that applied to classes farm and pet, and a different one that applied to classes mythical and wild. But I didn't want to write either piece of code twice. The solution was to use an intermediate ("abstract") class .. and have one of the pieces of code in the base class, and the other in the abstract class.