Click here to Skip to main content
15,881,380 members
Articles / Programming Languages / C#

Why I use explicit interface implementation as a default implementation technique

Rate me:
Please Sign up or sign in to vote.
4.86/5 (79 votes)
28 May 2012CPOL4 min read 132K   93   63
EIMIs turn to be very useful in refactoring. I will try to prove it here. If you are working with large code bases, as I often do, this article is worth reading.

Introduction

Implementing interfaces in C# is an everyday programmer task. Most interfaces are implemented using implicit technique without any doubt. Explicit implementation not only is unfamiliar, but is considered to be a some awkward solution to a very rare problem of implementing two interfaces with same members.

In this article I'm going to discuss, why, in my opinion, explicit interface implementation - EIMI - should be considered as the default implementation technique. And how using EIMIs keeps interfaces and their implementations in a coherent state.

Basics

For the beginning, let's recall what implicit and explicit interface implementation means.
Given an interface ILogger
C#
interface ILogger
{
    void Trace(string format, params object[] args);
}
We usually implement it in the following way
C#
class Logger : ILogger
{
    public void Trace(string format, params object[] args) { }
}
This is an implicit interface implementation.

The meaning of implicit here is - the compiler decides on its own that a public method Logger.Trace(...) will implement the corresponding ILogger.Trace(...) interface member.

Let's put the above explicitly

C#
class Logger : ILogger
{
    void ILogger.Trace(string format, params object[] args) { }
}

This is an explicit interface implementation - EIMI

What MSDN tells us about the need of EIMI?

Given two interfaces with the same members
C#
interface IControl
{
    void Paint()
}

interface ISurface
{
    void Paint()
}
We need a way to distinguish the same members if we are going to implement both of the interfaces in a single class
C#
public class SampleClass : IControl, ISurface
{
    void IControl.Paint() { }
    void ISurface.Paint() { }
}

The Key Difference of Explicit Implementation

Explicitly implemented methods and properties are private and inaccessible even to the implementing class
C#
interface ILogger
{
    void Trace(string format, params object[] args);
}

class Logger : ILogger
{
    void ILogger.Trace(string format, params object[] args) { }
}

void main()
{
    Logger log = new Logger();
    log.Trace("");    // Compilation error, Trace() is not accessible
}
Explicitly implemented methods can be accessed through interface only
C#
void main()
{
    ILogger log = new Logger();
    log.Trace("");    // Accessing through interface is OK
}

The Glory of the Explicit Implementation

Refactoring

Let's implement some simple interface ICalculator.
Then, let's trace revisions of the interface as software is being developed.
C#
interface ICalculator
{
    void Solve(int startPoint);
}

class BasicCalculator : ICalculator
{
    public void Solve(int startPoint) { }
}
Half a year later, obviously, the interface is enriched with an additional method
C#
interface ICalculator
{
    void Solve(int startPoint);
    void Solve(int startPoint, int endPoint);
}
In this half a year other stuff was added to BasicCalculator, as well. And here is what we might get after implementing the additional Solve(int startPoint, int endPoint) method
C#
class BasicCalculator : ICalculator
{
    public void Solve(int startPoint);
    
    // other very useful stuff
    
    public void Solve(int startPoint, int endPoint);
}
In another half a year a major refactoring takes place, and the first Solve(int startPoint) method is removed from the ICalculator interface.
C#
interface ICalculator
{
    // calculation with start point only is not good enough, method is removed
    
    void Solve(int startPoint, int endPoint);
}
Now, I will ask a question: "Do you know many programmers there who bother to go over all implementations and check if a particular change in interface leaves ghost public functions?"
C#
class BasicCalculator : ICalculator
{
    public void Solve(int startPoint);      // this one is left here forever
    
    // other very useful stuff
    
    public void Solve(int startPoint, int endPoint);
}
I doubt, that the answer is yes. So, the first version of Solve(int startPoint) method is left inside all implementations of ICalculator interface forever.

With explicit implementation this will not going to happen !

C#
interface ICalculator
{
    void Solve(int startPoint, int endPoint);
}

class BasicCalculator : ICalculator
{
    void ICalculator.Solve(int startPoint);    // Compilation error!
                                               // ICalculator has no such a method!    
    
    void ICalculator.Solve(int startPoint, int endPoint);
}

EIMI forces the compiler to look all over the code and tells us that we no longer need to implement the Solve(int) method.

In my opinion this "feature" is a killer and is a "must-to-use" in any large code base with many maintainers, especially if some of them are less experienced.

Decoupling From a Specific Implementation

There are other benefits of EIMIs as well.

Consider the following code

C#
interface ICalculator
{
    void Solve(int startPoint);
}

class BasicCalculator : ICalculator
{
    public void Solve(int startPoint);

    // unfortunately, methods like this one seem to appear by their self in any enterprise code base
    public void UseSinToSolveTheProblemIfStartPointIsZero(int startPoint);
}

void main()
{
    var calculator = new BasicCalculator();    

    // bad! dependency on a specific implementation
    calculator.Solve(123);
}

The var keyword is very convenient and commonly used. As a result, in the example above the calculator variable becomes an instance of the BasicCalculator class. This is obviously bad, since the code becomes coupled to a specific implementation of a general ICalculator interface.

Later an inexperienced maintainer, will be tempted to use the calculator.UseSinToSolveTheProblemIfStartPointIsZero() method.

With EIMI the main() above won't compile since Solve() method is not accessible within the BasicCalculator class. We are forced to use the explicit ICalculator declaration instead of just the var keyword

C#
void main()
{
    ICalculator calculator = new BasicCalculator();    

    // good! decoupled from a specific implementation
    calculator.Solve(123);
}

Decoupling Public Interface From Implementation Details

And the last (for this article) benefit of EIMI.
Consider this code
C#
interface ILogger
{
    string Name { set; }
}

class Logger : ILogger
{
    public string Name { get; set; }
    
    private void GenerateAutoName()
    {
        Name = "MySophisticatedLogger";
    }
}

Here a public property Name is used to implement a private implementation detail inside the GenerateAutoName() method.

Half a year later we will probably add a validation code for the Name property

C#
class Logger : ILogger
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set 
        {
            if (String.IsNullOrEmpty(value))
                throw new BadArgumentException();
                
            _name = value;
        }
    }
}
We no longer use the auto-implemented property feature of C#. But what happens inside our private GenerateAutoName() method? The validation code is "injected" into the method as well.
C#
private void GenerateAutoName()
{
    Name = "MySophisticatedLogger";
}

Do we need the validation code of external data inside internal implementation? I guess that the answer is no.

Avoiding use of own public methods in private implementation details is a good practice, IMHO.

C#
interface ILogger
{
    string Name { set; }
}

class Logger : ILogger
{
    public string ILogger.Name { get; set; }
    
    private void GenerateAutoName()
    {
        Name = "MySophisticatedLogger";        // compilation error!
    }
}
EIMI forces us to add private field _name as soon as we are going to use it in a private implementation.

Conclusion

In my every day programming I implement interfaces. The explicit way of implementing is the default for me. I use an implicit implementation only when I can not avoid it. Each time I'm refactoring, I see the actual benefits of EIMIs.

Here is a nifty implementation of a template method design pattern using EIMI

C#
interface ICalculator
{
    void Solve();
}

abstract class CalculatorBase : ICalculator
{
    protected abstract void CalculateSolution();
    
    void ICalculator.Solve()
    {
        CalculateSolution();
    }
}

I like the way the design is expressed here. The interface Solve() method delegates the implementation details to a protected virtual method overridden by descendants.

EIMI keeps code cleaner and more maintainable.

Farther Reading

What is EIMI? EIMIs are good EIMIs are bad

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer Cpp2Mtl Integration Solutions
United States United States
My real name is Reuven Bass. My first article here was published under the Mamasha Knows pseudonym. It worked. So, I stay with Mamasha for a while. (If it works - do not touch it)

Programming became my life from thirteen. I love coding. I love beauty. I always try to combine coding and beauty.

RB

Comments and Discussions

 
QuestionThis example with refactoring is a fail! Pin
Member 1232607813-Feb-16 23:27
Member 1232607813-Feb-16 23:27 
QuestionI have a different thought Pin
Shivprasad koirala12-Jun-15 3:47
Shivprasad koirala12-Jun-15 3:47 
AnswerRe: I have a different thought Pin
Reuven Bass15-Jun-15 22:31
Reuven Bass15-Jun-15 22:31 
GeneralRe: I have a different thought Pin
Shivprasad koirala17-Jun-15 17:33
Shivprasad koirala17-Jun-15 17:33 
QuestionMy vote of Pin
Reuven Bass17-Feb-15 6:05
Reuven Bass17-Feb-15 6:05 
GeneralYou are telling us to use Visual Basic instead of C# Pin
Tigerfink25-Sep-14 3:04
Tigerfink25-Sep-14 3:04 
QuestionMy rating is 5 Pin
Goel Himanshu15-Aug-14 20:20
professionalGoel Himanshu15-Aug-14 20:20 
AnswerRe: My rating is 5 Pin
Reuven Bass20-Aug-14 23:49
Reuven Bass20-Aug-14 23:49 
QuestionHere is another practical example: Pin
dietmar paul schoder2-Aug-14 10:26
professionaldietmar paul schoder2-Aug-14 10:26 
QuestionExcellent, Very Informative, Just one point Pin
qdev767-Nov-13 11:58
qdev767-Nov-13 11:58 
GeneralMy vote of 5 Pin
Joachim Blank17-May-13 1:26
Joachim Blank17-May-13 1:26 
GeneralMy vote of 5 Pin
Akhil Mittal3-Mar-13 20:38
professionalAkhil Mittal3-Mar-13 20:38 
GeneralMy vote of 5 Pin
S. M. Ahasan Habib3-Feb-13 6:02
professionalS. M. Ahasan Habib3-Feb-13 6:02 
GeneralMy vote of 5 Pin
Ivaylo Slavov16-Aug-12 0:44
Ivaylo Slavov16-Aug-12 0:44 
GeneralMy vote of 5 Pin
Ravi Lodhiya13-Jun-12 3:58
professionalRavi Lodhiya13-Jun-12 3:58 
GeneralRe: My vote of 5 Pin
Reuven Bass16-Jun-12 9:24
Reuven Bass16-Jun-12 9:24 
QuestionThanks for an interesting read Pin
TeaTime12-Jun-12 22:48
TeaTime12-Jun-12 22:48 
AnswerRe: Thanks for an interesting read Pin
Reuven Bass16-Jun-12 9:22
Reuven Bass16-Jun-12 9:22 
GeneralMy vote of 5 Pin
umlcat8-Jun-12 3:59
umlcat8-Jun-12 3:59 
GeneralRe: My vote of 5 Pin
Reuven Bass16-Jun-12 8:45
Reuven Bass16-Jun-12 8:45 
GeneralMy vote of 5 Pin
Oshtri Deka7-Jun-12 5:24
professionalOshtri Deka7-Jun-12 5:24 
GeneralRe: My vote of 5 Pin
Reuven Bass16-Jun-12 8:44
Reuven Bass16-Jun-12 8:44 
GeneralMy vote of 5 Pin
shenba20095-Jun-12 14:36
shenba20095-Jun-12 14:36 
best practice!
GeneralRe: My vote of 5 Pin
Reuven Bass16-Jun-12 8:44
Reuven Bass16-Jun-12 8:44 
GeneralMy vote of 5 Pin
Himanshu Thawait5-Jun-12 8:28
Himanshu Thawait5-Jun-12 8:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.