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:
- The implementing member has no access modifier (no public, private or protected).
- 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();
myInterface.Foo();
...or better yet, using your favorite dependency-injection framework:
using (var unity = new UnityContainer().LoadConfiguration())
{
IMyInterface unityInjected = unity.Resolve<IMyInterface>();
unityInjected.Foo();
}
Because explicit interface implementations force consumers of your class to go through the interface, they go a long way toward promoting loose coupling.