Hi,
As a long-time C++ programmer, I am always on the lookout for the dangers of the
inheritance diamond (possible in C++ because it allows multiple inheritance).
In my current C# program, I have just discovered I am doing the same thing but using interfaces, and I am wondering if it is functionally okay? Is it a bad practise, and if it is, how should I be looking to re-factor it?
This complete program shows an example of what I mean:
using System;
namespace ConsoleApplication1
{
public interface IBaseService
{
int X { get; }
}
public interface ISpecificService : IBaseService
{
int Y { get; }
}
public abstract class ServiceBase : IBaseService
{
public int X { get { return 42; } }
}
public class ConcreteClass : ServiceBase, ISpecificService
{
public int Y { get { return 43; } }
}
class Program
{
static void Main( string[] args )
{
ConcreteClass c = new ConcreteClass();
Console.WriteLine( $"X={c.X.ToString()}, Y={c.Y.ToString()}" );
Console.ReadKey();
}
}
}
Output is: 'X=42, Y=43'.
Any advice or pointers to useful articles would be very much appreciated.
To give a bit more detail about the real-world situation, I have the following:
I have an
IBaseService
, which is the core contract that all my services must implement. No 'base-class' implementation is possible for these functions and hence it needs to be an interface.
I have specific services, which must implement the core contract but also add their own requirements to the contract. Once again, no 'base-class' implementation of these is possible, so these specific services also need to be interfaces.
I also would like to have a home for some other functionality that does have a 'base-class' concrete implementation, and so I have an abstract
ServiceBase
for this code.
Any concrete service thus gets the benefit of the concrete common code from the
ServiceBase
but then has to implement the contract dictated by the chain of interfaces it also inherits.
It all seems quite logical, and I struggle to see which bits I could do differently without reducing the chance that a new programmer (or me in a week's time) might come along and write a new service that doesn't fulfil all of its obligations and can take advantage of common code.
It's easier to code than explain. Hope this makes sense.
Kind wishes ~ Patrick
What I have tried:
I've tried the code above, obviously, which works fine. Guess I am more bothered about something being seriously wrong with the design.