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?
Share
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 . 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 something happens by an implementer of the interface. If you require that something happens, then you don’t want to provide an interface at all–and you would also need to make sure that your base class ensures this required action to ALWAYS occur…
Negative to doing both: more goo.
example pseudocode:
Note that in this example, someone could make their own class that implements
IVehicleand then pass it to anything that takes anIVehicle. That object would NOT need to be a child of theVehicleabstract class. If, therefore, you were to expect something specific to happen in thePutCarInGear()method, it’s quite likely that that new class would NOT fulfill that expectation. However, as long as it never matters what implementations ofIVehicledo, then it’s the most flexible abstraction to have both an abstract base class AND an interface.