5

.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
    }
}
user1194528
  • 395
  • 1
  • 4
  • 10
  • 6
    This is a **very** awkward pattern you're trying to implement. You said *".NET does not allow partial interface implementation in base classes."* - there's a reason for that. Client code kind of expects something that **implements an interface** to, you know, maybe... **implement the interface**. Throwing exceptions for unsupported methods as a matter of course is *very* bad code smell... – Yuck Feb 07 '12 at 12:47
  • Agree with Yuck. If you have a variable of type `IFoo`, you really expect all methods of `IFoo` are implemented and available. Interfaces are made for that. – ken2k Feb 07 '12 at 12:51
  • Only MyClass1 _must_ fully implement interface. And it does. Problem is that there are multiple child classes (I didn't mention it earlier), each must implement IFoo. Without base class you must copy/paste Method1 implementation, which is equal for all child classes. This is what I'm trying to avoid. But Method2 implementation is different in child classes, so I can't have just one class that implements both Method1 and Method2. – user1194528 Feb 07 '12 at 13:11
  • Another clarification. There is a net of communicating objects. If anything is implemented just as public methods, you may be lost trying to understand what this method does, who uses it and how can you change/refactor it. To reduce complexity I use interfaces. Each interface defines interaction between two classes (with all their children). Part of interface implementation is common for all classes in hierarchy, other vary in children. This is a root for my problem. You have to choose between copy/paste, complex class contracts and awkward constructs I mentioned earlier. – user1194528 Feb 07 '12 at 13:33

4 Answers4

9

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
    }
}
numerek
  • 177
  • 1
  • 7
6

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();
}
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • This is my variant #2 except for first disadvantage. Still apply: 1. has to put additional obsolete construct to prevent direct method call from child classes. In your case there are no Obsolete, so direct call from child class would not generate compile time warning 2. 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. Less readable. You don't see that Method2 is IFoo implementation. – user1194528 Feb 07 '12 at 13:38
  • Reading the comments below the question, this does seem to be the correct way to solve the problem. An abstract implementation of `Method2()` in `BaseClass` ensures that `IFoo` is fully implemented, while at the same time forcing all classes deriving from `BaseClass` to implement `Method2()`. It can also be added that derived classes will _not_ be able to override `Method1()` (but they will be able to _hide_ it (using the `new` keyword)). – Julian Feb 07 '12 at 13:41
  • @user1194528 What's your actual problem with the code above? Why do you want to put Obsolete annotations? – ken2k Feb 07 '12 at 13:43
  • 2 user1194528: Obsolete annotations needed to prevent accidental call of Method2 from within MyClass1. Because it must be called only by IFoo client – user1194528 Feb 07 '12 at 14:22
  • 2 Nailuj: You are right. But this method has slight drawbacks I described above – user1194528 Feb 07 '12 at 14:29
  • 2 user1194528: It may seem overprotective, but you would want minimal accessibility approach when you have hierarchy of 10+ classes, each interacting with 3-4 other classes. Declare all methods public, leave the code in hands of inexperienced coders, and this mess is almost impossible to refactor. – user1194528 Feb 07 '12 at 14:41
5

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)
Community
  • 1
  • 1
oleksii
  • 35,458
  • 16
  • 93
  • 163
  • 1
    I thought of interface segregation, but the problem is that interface design comes from client class needs, not server class. Client class doesn't want to know implementation details. Why it should know that some part if this interface is implemented in base class and other in children? It's also very fragile there may be two class hierarchies that implement this interface and they are different in a way how implementation is split between base class and child class. – user1194528 Feb 07 '12 at 14:13
0

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.

supercat
  • 77,689
  • 9
  • 166
  • 211
  • >>it's impossible for the child's re-implementation of the interface to chain to the parent's implementation. - good point. From this perspective it's better to declare all methods as protected (+abstract for those, not implemented) (ken2k variant). Thanks 2 all for you thoughts. Now I can make more informed decision. – user1194528 Feb 08 '12 at 17:37