简体   繁体   中英

C# best partial interface implementation in base/abstract class

.net does not allow partial interface implementation in base classes. As a mitigation I've come to 3 alternate solutions. Please help me decide which is more universal in terms of refactoring, compile/run time errors, readability. But first a couple of comments.

  • Of course you may always cast object to IFoo and call any method without any compiler warning. But it's not logical, you wouldn't do that normally. This construct wouldn't occur as a result of refactoring.
  • I want maximum separation. Direct class contract (public methods and properties) should be separated with interface implementations. I use interfaces a lot to separate object interations.

My comparison:

  1. BaseClass1/MyClass1:
    • con: Have to create virtual abstract in BaseClass1 for each not implemented method of IFoo.
    • con: Additional method wrap - slight productivity impact at runtime.
  2. BaseClass2/MyClass2:
    • con: no compiler warning if no implementation of Method2 in MyClass2. Runtime exception instead. Refactoring with poor unit test coverage may potentially destabilize code.
    • con: has to put additional obsolete construct to prevent direct method call from child classes.
    • con: Method2 is public for BaseClass1 so it's part of class contract now. Have to put "Obsolete" construct to prevent direct call, not via IFoo.
  3. BaseClass3/MyClass3:
    • pro: (Compared to #2). More readable. You see that MyClass2.Method2 is IFoo implementation, not just some overriden method.
public interface IFoo
{
    void Method1();
    void Method2();
}
public abstract class BaseClass1 : IFoo
{
    void IFoo.Method1()
    { 
        //some implementation
    }

    void IFoo.Method2()
    {
        IFooMethod2();
    }

    protected abstract void IFooMethod2();
}

public class MyClass1 : BaseClass1
{
    [Obsolete("Prohibited direct call from child classes. only inteface implementation")]
    protected override void IFooMethod2()
    {
        //some implementation
    }
}
public abstract class BaseClass2 : IFoo
{
    void IFoo.Method1()
    {
        //some implementation
    }

    [Obsolete("Prohibited direct call from child classes. only inteface implementation")]
    public virtual void Method2()
    {
        throw new NotSupportedException();
    }
}

public abstract class MyClass2 : BaseClass2
{
    public override void Method2()
    {
        //some implementation
    }
}
public abstract class BaseClass3 : IFoo
{
    void IFoo.Method1()
    {
        //some implementation
    }

    void IFoo.Method2()
    {
        throw new NotSupportedException();
    }
}

public abstract class MyClass3 : BaseClass3, IFoo
{
    void IFoo.Method2()
    {
        //some implementation
    }
}

I like this version, the base class can't be instantiated because its abstract, the derived class must list IFoo in its declaration or else it won't be implementing the interface and then it is solely responsible for implementing the rest of the interface. One drawback I can see is you can't explicitly implement the interface methods in the base class (ie no IFoo:Method1), but otherwise this is a fairly low overhead version.

public interface IFoo
{
    void Method1();
    void Method2();
}

public abstract class BaseClass1
{
    public void Method1()
    {
        //some implementation
    }
}

public class MyClass1 : BaseClass1, IFoo
{
    public void Method2()
    {
        //some implementation
    }
}

It is extremely bad to design a class that doesn't implement a well-defined contract. It is extreme because you firstly say that a class is capable of doing something. You explicitly highlight that the class can do stuff, but later in the code you say nahh, screw it, this class can live without implementation. Compiler very wisely asks you to implement the contract, but it is left up to you to decide.

Here are some common solutions

Bad solution

  • Throw an exception (NonImplementedException or NotSupportedException, see sample )
  • Declare it as obsolete (design it good from the beginning)

Better solution

  • Explicit interface implementation, but you still implement it (just kind of hide it)

Best solution

  • Use interface segregation (split your fat interface into thinner and more manageable ones)

Ok, you could try the following as BaseClass is abstract:

public interface IFoo
{
    void Method1();

    void Method2();
}

public abstract class BaseClass : IFoo
{
    public void Method1()
    {
        // Common stuff for all BaseClassX classes
    }

    // Abstract method: it ensures IFoo is fully implemented
    // by all classes that inherit from BaseClass, but doesn't provide
    // any implementation right here.
    public abstract void Method2();
}

public class MyClass1 : BaseClass
{
    public override void Method2()
    {
        // Specific stuff for MyClass1
        Console.WriteLine("Class1");
    }
}

public class MyClass2 : BaseClass
{
    public override void Method2()
    {
        // Specific stuff for MyClass2
        Console.WriteLine("Class2");
    }
}

private static void Main(string[] args)
{
    IFoo test1 = new MyClass1();
    IFoo test2 = new MyClass2();

    test1.Method2();
    test2.Method2();

    Console.ReadKey();
}

I'd suggest having the abstract base class implement the interface with methods that call protected abstract methods, as shown in your first example, except for methods which some derived classes may not implement (following the "throw everything into IList but don't have all the methods actually work" pattern); those could be protected virtual stubs which throw NotSupportedException .

Note that it is up to the child class whether to expose any particular member of the interface as a like-named public member (which could call the appropriate abstract member).

The proper pattern in VB.net would be something like MustOverride Sub IFoo_Method1() Implements IFoo.Method1 , which would avoid the extra function call overhead, but C# doesn't provide any means of implementing an interface with a protected member. Using explicit interface implementation for any method which may have to be overridden in a child class is somewhat icky, because it's impossible for the child's re-implementation of the interface to chain to the parent's implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM