I have a number Processor classes that will do two very different things, but are called from common code (an “inversion of control” situation).
I’m wondering what design considerations I should be cognicent (or cognizant, for you USsers) of when deciding if they should all inherit from BaseProcessor, or implement IProcessor as an interface.
Generally, the rule goes something like this:
To put this in somewhat more concrete terms, let’s look at an example. The
System.Drawing.Bitmapclass is-an image (and as such, it inherits from theImageclass), but it also can-do disposing, so it implements theIDisposableinterface. It also can-do serialization, so it implements from theISerializableinterface.But more practically, interfaces are often used to simulate multiple inheritance in C#. If your
Processorclass needs to inherit from something likeSystem.ComponentModel.Component, then you have little choice but to implement anIProcessorinterface.The fact is that both interfaces and abstract base class provide a contract specifying what a particular class can do. It’s a common myth that interfaces are necessary to declare this contract, but that’s not correct. The biggest advantage to my mind is that abstract base classes allow you provide default functionality for the subclasses. But if there is no default functionality that makes sense, there’s nothing keeping you from marking the method itself as
abstract, requiring that derived classes implement it themselves, just like if they were to implement an interface.For answers to questions like this, I often turn to the .NET Framework Design Guidelines, which have this to say about choosing between classes and interfaces:
Their general recommendations are as follows:
Chris Anderson expresses particular agreement with this last tenet, arguing that: