Minimize Boilerplate

59 Views Asked by At

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()
    {
        //...
    }

    //...
}
1

There are 1 best solutions below

0
user700390 On BEST ANSWER

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;
}