Class Design – Should a Class Know About Its Subclasses?

classclass-designobject-orientedobject-oriented-design

Should a class know about its subclasses? Should a class do something that is specific for a given subclass for instance?

My instincts tells me that is a bad design, it seems like an anti-pattern of some sort.

Best Answer

The answer implied by the concept of classes is "no".

Either whatever action, data or relation you're handling is part of all subclasses - then it should be handled in the superclass without checking the actual type. Or it applies only to some subclasses - then you'd have to perform run-time type checks to do the right thing, the superclass would have to be changed whenever someone else inherits from it (or it might silently do the wrong thing), changes in the derived classes can break the unchanged superclass, etc.

In short, you get a number of bad consequences which are usually bad enough to reject such solutions out of hand. If several of your subclasses do the same thing and you want to avoid code duplication (practically always a good thing), a better solution is to introduce a mid-level class from which all those subclasses can inherit the code.

Related Topic