I recently asked this question on if I should implement interfaces or abstract classes. Scottm gave answer suggesting I use both, but I am still unsure why I would want to do this. Is there a benefit in the long term? What are advantages of doing it that way?
Here are some benefits I think:
Here is another question. If I implement an interface, should the interface only contain methods that all sub-classes can do? And if I need extra logic, I would create a concrete class or abstract class with more specific implementations.
This approach gives you the best of both worlds - the flexibility of interfaces with the helpful option of a base class.
By requiring only that consumers implement your interface, you are not forcing them to lose the only inheritance slot open to their class (C# not allowing multiple inheritance).
But by additionally offering an abstract base class, you can give them a "leg up", perhaps by implementing some helper functionality that is likely to be a common requirement to most implementations of your interface - for example this could be achieved using a Template Method pattern.
There are several examples in the .NET Framework itself of both an interface and a base class being exposed. For example System.ComponentModel.IComponent
and System.ComponentModel.Component
Here is another question. If I implement an interface, should the interface only contain methods that all sub-classes can do?
Yes. You're essentially describing the Interface Segregation Principle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With