Promote Loose Coupling with Explicit Interface Implementation

by Larry Spencer Monday, January 30, 2012 8:34 PM

Like every good developer, one of your New Year's Resolutions was to program to interfaces rather than to concrete classes. (Right?) So now you have gone to all the trouble of lovingly crafting an interface as well as a class:


public interface IMyInterface
    void Foo();


public class MyImplementation : IMyInterface
    public void Foo()
        // Do something.


The next thing you know, one of your teammates -- unaware of your new way of life -- goes off and codes something like this:


new MyImplementation().Foo();


Argh!!! He has totally violated every principle you now hold dear.

What can you do to prevent this travesty?

One strategy is to make your class implement the interface explictly. (Visual Studio can help. Right-click on the IMyInterface inheritance and then select Implement Interface --> Implement Interface Explicitly.)


public class MyExplicit : IMyInterface
    void IMyInterface.Foo()
        // Do something


You'll notice two things:

  1. The implementing member has no access modifier (no public, private or protected). 
  2. The method name, Foo, is preceded by the name of the interface.

When you thus implement an interface explicitly, nobody can call the interface's methods and properties directly on the concrete object! They must call through the interface:


IMyInterface myInterface = new MyExplicit();


...or better yet, using your favorite dependency-injection framework:


using (var unity = new UnityContainer().LoadConfiguration())
    IMyInterface unityInjected = unity.Resolve<IMyInterface>();


Because explicit interface implementations force consumers of your class to go through the interface, they go a long way toward promoting loose coupling.


All | Dependency Injection | General

Pingbacks and trackbacks (2)+

Add comment

About the Author

Larry Spencer

Larry Spencer develops software with the Microsoft .NET Framework for ScerIS, a document-management company in Sudbury, MA.