Click here to Skip to main content
15,879,095 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 131.9K   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

 
GeneralRe: My vote of 5 Pin
Reuven Bass28-May-12 22:25
Reuven Bass28-May-12 22:25 
GeneralWell thought out Pin
Stephen Inglish28-May-12 18:00
Stephen Inglish28-May-12 18:00 
GeneralRe: Well thought out Pin
Reuven Bass28-May-12 20:34
Reuven Bass28-May-12 20:34 
GeneralUseful. Pin
podirton28-May-12 16:58
podirton28-May-12 16:58 
GeneralRe: Useful. Pin
Reuven Bass16-Jun-12 8:38
Reuven Bass16-Jun-12 8:38 
GeneralMy vote of 5 Pin
yimlu28-May-12 15:25
yimlu28-May-12 15:25 
GeneralRe: My vote of 5 Pin
Reuven Bass16-Jun-12 8:39
Reuven Bass16-Jun-12 8:39 
SuggestionI know this is probably knitpicking... Pin
nortee28-May-12 13:42
nortee28-May-12 13:42 
Hi,

I just have one question. I have been using interfaces and inheritance as well as OO type design patterns for a while now, and based on that and the fact that I use inheritance more than interfaces, how is this implementation different from this type of methodology (as a very simple example) that you describe in your article?:
public abstract class Something
{
    public abstract int GetSomeValue();

    public int MyValue
    {
        return (GetSomeValue());
    }
}

public class MyBaseImplementation : Something
{
    protected override int GetSomeValue()
    {
        return (1);
   }
   
}

public class MyImplementation2 : MyBaseImplementation
{
   protected override int GetSomeValue()
   {
       return (2);
   }
}

public class MyImplementation3 : MyBaseImplementation2
{
   protected override int GetSomeValue()
   {
       return (base()+1);
   }
}

public void main()
{
    Something test;
    test = new MyBaseImplementation();
    // return the value somewhere
    test = new MyBaseImplementation2();
    // return the value somewhere
    test = new MyBaseImplementation3();
    // return the value somewhere
}

And no, I am not dissing your approach, I am just curious Smile | :) ... And yes, I know that it is the same as what you are saying (well... it almost looks the same but it isn't).

As far as I know, using interfaces tends to be more 'intensive' (based on the application needing to determine which implementation to use) as opposed to the compiler knowing what it needs to do when you want something to be done. Yes, I could probably be stood to be corrected here considering the power we have on even a cellphone now.

Let me know your thoughts are on this. And no I have not had the time to build an app that verifies the time between calls using the different techniques (I would love to test this), so if anyone has the time to verify that my suspicions are correct (although I think that might be regarding the interface method taking longer to process than the 'normal' inheritance methodology), please please let me know Smile | :) ...

In the meantime, I really like your approach and you have my 5 Smile | :) ...
my code might not be very complete, but I think you know what I mean Smile | :)
Cheers,
Glen Vlotman
"You cannot code for stupidity"


modified 28-May-12 20:21pm.

GeneralRe: I know this is probably knitpicking... Pin
aSarafian28-May-12 20:39
aSarafian28-May-12 20:39 
GeneralRe: I know this is probably knitpicking... Pin
Reuven Bass28-May-12 22:25
Reuven Bass28-May-12 22:25 
GeneralRe: I know this is probably knitpicking... Pin
Rafael Nicoletti6-Jun-12 0:35
Rafael Nicoletti6-Jun-12 0:35 
GeneralRe: I know this is probably knitpicking... Pin
nortee24-Jun-12 12:47
nortee24-Jun-12 12:47 
GeneralMy vote of 5 Pin
Omar Gameel Salem28-May-12 8:08
professionalOmar Gameel Salem28-May-12 8:08 
GeneralRe: My vote of 5 Pin
Reuven Bass28-May-12 10:32
Reuven Bass28-May-12 10:32 
GeneralRe: My vote of 5 Pin
BloodyBaron29-May-12 9:34
BloodyBaron29-May-12 9:34 

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.