Interfaces vs. Abstract Base Classes Revisited

posted on 09/09/07 at 09:27:08 pm by Joel Ross

I thought this issue had been beaten to death in the past year, but I figured I'd check out Kirill Osenkov's take on interfaces vs. abstract base classes, and, as is the norm, I took something away from it that I wasn't expecting to. I'd pretty much thought of them as essentially interchangeable, with the decision coming down to whether you had a default implementation or not.

Kirill points out that interfaces are better used to add or define features or abilities of a class. For example, IEnumerable doesn't define a list. It just adds the ability to enumerate over the items in a list. By contrast, a base class defines the derived class. If you have an Animal base class and Dog and Cat inherit from it, it's because Dogs and Cats ARE animals. If a Dog and Cat implement IPet, that's a feature of certain animals.

Don't get me wrong. I've been doing things this way. In our framework, we have the ISaveable interface - it's a feature of an Entity, so it's an interface. We have EntityBase, which is our base class for all Entities - because EntityBase defines all entities. It's just that I haven't seen it written out quite the way Kirill did - and it crystalized it for me.

And in case you only read part of Kirill's post, towards the bottom is interesting as well, where he warns against "burning the base class" - inheriting from a class just to add a small piece of functionality, while losing the ability to add any other type of functionality. It's good advice, although I think he takes it too far when he says an interface should only define one member. Sometimes, one member isn't enough to define an ability. I still think an interface should define one ability, but I think it's too limiting to say one member per ability.

Categories: Development, C#