Search code examples
c#boilerplate

Minimize Boilerplate


I need to implement some classes that inherit from the interface below. Many of the implementations differ only in the value returned by P. How can I minimize the number of lines of code?

public class A // I cannot change it
{
    public A(string _) { }
    //...
}

public interface I // I cannot change it
{
    A P { get; }
    void f();
    //...
}

public class B : I // many similar classes: they differ by signature, only
{
    public static A StaticP => new A("signature");

    public A P => StaticP;

    public void f()
    {
        //...
    }

    //...
}

Solution

  • You can move the code from f(), etc. into an abstract base class. Something like this:

    public abstract class BaseI : I
    {
        public abstract A P { get; }
    
        public void f()
        {
            //...
        }
    
        //...
    }
    
    public class B : BaseI
    {
        public static A StaticP => new A("signature");
    
        public override A P => StaticP;
    }