Since interfaces cannot contain implementation, that seems to me to lead to code duplication in the classes that inherit from the interface. In the example below, pretend that, let’s say, the first 10 or so lines that setup reading from a Stream are duplicated. Try not to focus on the wording here, but, instead focus on the concept of how easy it is to create duplicate code between each class.
For example:
public interface IDatabaseProcessor
{
void ProcessData(Stream stream);
}
public class SqlServerProcessor : IDatabaseProcessor
{
void ProcessData(Stream stream)
{
// setting up logic to read the stream is duplicated code
}
}
public class DB2Processor : IDatabaseProcessor
{
void ProcessData(Stream stream)
{
// setting up logic to read the stream is duplicated code
}
}
I realize that using an abstract base class for ProcessData and adding non-abstract members is one solution. However, what if I really, really want to use an interface instead?
The best way to share the code across interfaces is through stateless extension methods. You can build these extensions once, and use it in all classes implementing the interface, regardless of their inheritance chain. This is what .NET did with
IEnumerable<T>in LINQ, for rather impressive results. This solution is not always possible, but you should prefer it whenever you can.Another way to share logic is by creating an internal “helper” class. This looks like the right choice in your case: implementations can call the internally shared code as helper’s methods, without the need to duplicate any code. For example:
The helper class does not need to be static: if your shared methods need state, you can make your helper a regular class, and put an instance of it in each implementation of your interface where you would like to share code.