views:

74

answers:

4

When designing my software, I began with interfaces since this seems to be the "standard". Then I switched to abstract classes because they seem better suited to the problem at hand. However I'm not sure if I've missed out on some considerations when making this design choice. Other than domain specific issues which I have thought about what are the more general factors to consider when choosing between interfaces and abstracts classes?

+1  A: 

Inheritance defines similarity of composition. Interfaces define similarity of behavior. From there you have to decide if the composition is important enough to override the behavior.

Ignacio Vazquez-Abrams
A: 

If your interface also has reasonable default behavior for at least some of the functionality, you may want to use an abstract class to avoid common boilerplate code in all of the concrete implementations. Otherwise, use an interface.

dsimcha
A: 

Use an abstract class when you have multiple instances that reify the Template Method pattern.

Say you have three parsers. One deliminates the file's data by ",", another by " ", and another by "|"

You can then have a CommaParser, a SpaceParser and a PipeParser, all subclassing the Abstract Parser, and overriding the abstract method, getDelimiter()

Use an interface when the classes don't share implementation, but merely respond to the same method calls.

Alex Baranosky
+1  A: 

I find the best option most of the time is to do both. That is not always possible when you are relying on something happening in the base class (but I would wonder if you designed the class properly in that case). Providing both an abstract base class and an interface allows the greatest latitude by implementers of your abstraction, again, as long as you don't require a side-effect that you write into your abstract base class.

Negative to doing both: more goo.

example pseudocode:

interface IVehicle
{
    void PutCarInGear(Int speed);
}

abstract class Vehicle : IVehicle
{
    public void Drive(Int speed)
    {
        PutCarInGear(); // private method of base class maybe
        // more implementation
    }
}

implementers can choose either the abstract base class if they want the base implementation or the interface if they want/need to roll their own. Again, this is predicated upon you being able to decide/accept that someone can choose to implement just the interface--nothing in the base class can be required to make an implementation of just the interface (IVehicle in the example above) work correctly.

Kevin Won