12.03.08

Interfaces vs. Classes

Posted in Uncategorized at 8:01 pm by Kyoryu

As a follow-up to the last post, consider this:

Classes map to nouns.  They say what something is (a Person, for instance).

Interfaces map more closely to adjectives – they describe the noun (specifically, what the noun can do).

So, you wouldn’t have the class Person implement IPerson.  That’s basically saying that a person is person-y, which doesn’t make a lot of sense.

A person might implement IFeedable, IHirable, etc.

One thing that occurs to me as I write this post is that interfaces don’t describe what their nouns can do so much as they describe what can be done to the nouns.  This gets into the idea I have that most languages are very good at describing incoming messages to an object, but don’t do a very good job at describing outgoing messages.  But, that’s a topic for another day.

If this is true, then interfaces and classes serve very different purposes.  An interface shouldn’t be simply seen as the ultimate abstract base class.

If an interface is used to describe what can be done to a class (a Person might be IHirable), then in many cases, a class may implement multiple interfaces.  If that’s the case, then each interface should consist only of the actions that are atomic with that concept.  Actions that only make sense together, and don’t ever make sense without each other.

For instance, IHirable obviously needs some sort of Hire() method.  And, it might make sense for it to have a Fire() method.  It doesn’t make sense (legal reasons and internal politics aside) to be able to hire someone without being able to fire them.  And, similarly, you can’t fire someone that wasn’t able to be hired in the first place.  So, Fire() should go in IHirable, as it’s tightly coupled to Hire().

What about Pay()?  It doesn’t make sense that you can hire someone and not pay them, so it might make sense to put it in IHirable.  But, there are a lot of people that you pay that you don’t hire, and in fact, can’t hire.  The pizza delivery guy, the water company, etc.  So, maybe Pay just belongs in IPayable, which IHirable can extend.

Here’s a statement I’ll put forth, but I’m not backing 100% yet:

Having an interface with the same name as a class is a design smell.

 

Leave a Comment

You must be logged in to post a comment.