I don't think it's an either/or. I think you should use both Interfaces and Abstract Classes.
TL;DR
Abstract Classes
Pros:
- Relatively simple
- You can provide basic functionality and "hooks" that the subclasses can use.
Cons:
- You're "stuck" with the inheritance hierarchy
- Client code knows about the Base Class
Interfaces
Pros:
- Almost unlimited flexibility
Cons:
- Zero implementation provided
- May be harder for less experienced coders to understand.
Scenario
Imagine that you create an Abstract Class today. We'll call it BaseReport
. BaseReport provides an empty "save" method, and all your current types of reports extend from BaseReport and have their own implementation of save.
For the sake of argument, you also want to display the text of the report before saving it, so your BaseReport extends a simple View component provided by your language of choice that will allow you to put a few text objects and a save button on the screen and not much more. It's really lightweight, so it's a good choice based on all the reports you have in front of you. I'll call it SimpleContainer
.
Now, you're nine months down the line, and you need to have a report that has multiple pages, and someone has asked that one of the reports be viewable in either portrait or landscape modes. Neither of these requirements can be fulfilled with a subclass of SimpleContainer.
However, you have a lot of client code that knows about BaseReport, and there might even be a place or two where you've cast to SimpleContainer (where's the harm?). Not only that, the code is more like custom framework code, and you've spawned off four projects that use it. So all of those projects will have to go through QA again if you refactor to go to IReport so you can extend PagedContainer
for the one report and RotatableContainer
for the other. More than likely, at this point your answer is "sorry, we can't do that." Not because you really can't do that, but because it's too much of a risk to all the other things sitting on top of it.
But for the past 9 months, you've been developing along like gangbusters because you had that base code in BaseReport that allowed you to rip out a new Report type in record time, so you don't want to throw the baby out with the bathwater. Instead, make your BaseReport implement IReport and just make sure that the client code only refers to it as IReport. When the requirement comes in for a PagedContainer, build a BasePagedContainer that implements IReport and then build your individual reports on top.
There's not really a downside to this approach, because the amount of labor it takes to create the interface and implement it into your Abstract Classes is minuscule compared to the amount of flexibility and future-proofing you gain.
And I might have changed a few details to protect the innocent, but the scenario is real, and it happened to me. :)
ISaveable
. Interface names typically embody abilities.