Explicit interface implementation

Explicit interface implementation

In C# you have a feature, which java don’t have. It’s called explicit interface implementation.
The main use of this feature is to solve problems when you have to implement for example two interfaces which have both unfortunatly a same method signature:

namespace testpw.ExplicitInterfaces
{
    public interface IA
    {
        void doAction();
    }

    public interface IB
    {
        void doAction();
    }
}

The implementation of both interfaces on the same class look now like this:

namespace testpw.ExplicitInterfaces
{
    public class TestImpl : IA, IB
    {
        void IA.doAction()
        {
            Console.WriteLine(“Called doAction on interface IA”);
        }

        void IB.doAction()
        {
            Console.WriteLine(“Called doAction on interface IB”);
        }
    }
}

One of the benefit of the exlicit interface implementation is, that you could solve this a little bit exotic problem. An other possibility to use explicit interface implementation is, when you have an existing object-structure and you have to extend it with some infrastructure-logic. This new logic you want to hidden to the consumer of the object-structure, so you could use the explicit interface implementation to hide this new logic.

But, I saw also other interpretations how to use the explicit interface implementation:

  • Use an interface as bracket to hold the logic together, which is used in an UseCase
  • Implement diffrent UseCases on the same class and the only separation was by implementing the logic through explicit interface implementation.

Those interpretation of the explicit interface implementation is from my point wrong. They are anti-patterns.
For the first interpretation ignores, that for that reason exists classes.
The second interpretation is even worse. It hurts the encapsulation on an object. If you implement severals inteface in an explicit manner and you add to this class a private metod for one of those interfaces, this private method is also visible for the other interface implementations. This interpretation hurts also the principles “single-responsibilty” or “separation-of-concerns”. The implemention (the class) has to be modified when one of the interface implementation has to be fixed.

My advice for explicit interface implementation is to use it only in the two described cases. Don’t try to find an other encapsulation mechanism for classes, use classes for this need.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.