Interfaces, Abstact Classes and Base Classes, oh my!

The discussion came up today, due to a comment of mine, about Interfaces. When should you use them? When should you use a simple base class? I, of course, gave my own opinion on the topic and my team discussed the current project environment to come to a decision on how to proceed.

Afterwards I began doing a bit more research on the subject. One of the articles I ran across was by Mahesh Singh. He put together a very nice overview entitled Abstract Class vs Interface. Essentially it comes down to this question; Will there be shared implementation among inherited classes? His suggestion is that in most cases it is better to use an abstract class. There are a few good comments as well. One reader gives you an exercise which may make things more clear and potentially swing you more towards the need for interfaces, but I’ll leave that up to you.

In the article Interface vs Abstract Class by Maor David he describes some of the differences between interfaces and abstract classes. This article does not try to answer the question of which is better so much as to inform.

It is my opinion that every situation is different. I do not believe either is inherently better than the other; rather, I believe that each is better in certain circumstances. That puts the onus of deciding which road to go down on the developer to decide which suites the condition.

The point that is perhaps more important is to realize that you won’t always get it right. If not, don’t be afraid to refactor! At the same time, don’t be afraid to look at it and say…meh…it’s good enough. The gain for refactoring to use x would not be worth the time it involved.


3 thoughts on “Interfaces, Abstact Classes and Base Classes, oh my!

  1. I agree on both counts. πŸ˜€ The article by Maor David was more of an informational whereas Mahesh’s was his opinion and reasoning for it. I like the information to help me make my own decisions.

  2. I think I use interfaces and plain old base classes more than abstract classes. Usually I’ll inherit from a base class and override a function to change it’s behavior. If I have multiple implementations a small interface often fits better for me.

    And I don’t think I use inheritance nearly as much as the intro to object oriented stuff suggests. I try to do a lot more with composition of small objects.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s