I have a bunch of systems, lets call them A, B, C, D, E, F, G, H, I, J.
They all have similar methods and properties. Some contain the exact same method and properties, some may vary slightly and some may vary a lot. Right now, I have a lot of duplicated code for each system. For example, I have a method called GetPropertyInformation() that is defined for each system. I am trying to figure out which method would be the best approach to reduce duplicate code or maybe one of the methods below is not the way to go:
Interface
public Interface ISystem
{
public void GetPropertyInformation();
//Other methods to implement
}
public class A : ISystem
{
public void GetPropertyInformation()
{
//Code here
}
}
Abstract
public abstract class System
{
public virtual void GetPropertyInformation()
{
//Standard Code here
}
}
public class B : System
{
public override void GetPropertyInformation()
{
//B specific code here
}
}
Virtual Methods in a Super Base class
public class System
{
public virtual void GetPropertyInformation()
{
//System Code
}
}
public class C : System
{
public override void GetPropertyInformation()
{
//C Code
}
}
One question, although it may be stupid, is let’s assume I went with the abstract approach and I wanted to override the GetPropertyInformation, but I needed to pass it an extra parameter, is this possible or would I have to create another method in the abstract class? For example, GetPropertyInformation(x)
Your abstract and ‘super base class’ approaches are not too different. You should always make the base class abstract, and you can provide a default implementation (virtual methods) or not (abstract methods). The deciding factor is whether you ever want to have instances of the base class, I think not.
So it’s between base class and interface. If there is a strong coupling between your A, B C classes then you can use a base class and probably a common implementation.
If the A, B, C classes do not naturally belong to a single ‘family’ then use an interface.
And
Systemis not such a good name.And you cannot change the parameterlist when overriding. Maybe default parameters can help, otherwise you just need 2 overloads for GetPropertyInformation().