I’ve just been handed an API that seems to be a step up from what I’m used to, as everything appears to be implemented using interfaces, and I’m struggling to get my head around them.
public partial class Form1 : Form, IFoo
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Guid jobID = AddBarToFoo(fooID, barPath);
}
public Guid IFoo.AddBarToFoo(string fooID, string barPath)
{
throw new NotImplementedException();
}
So that’s a basic structure. Visual Studio has kindly implemented the interface in its entirety and I can call the AddBarToFoo method. Great.
But now what? Evidently the method is a void that requires some code, but what code? Should I be scouring the API for objects to instantiate with that method? Or am I going down completely the wrong path?
That’s the thing with interfaces. They only define how someone will call them. They say absolutely nothing about what the method should really do, or how it should do it. That’s up to the person implementing the interface to decide.
VS “implements” the method by adding the single line
throw new NotImplementedException();which is really just to satisfy the compiler.Here’s two possible (contrived) implementations that do totally different things. Both implement
IFoo:Edit… You’ll see interfaces used a lot in places where the abstract behavior is important, but the implementation can vary. For instance, an interface to persist objects. During development you might want to use a mock that puts and gets items into a list in memory. Later you might use an interface that directly hits a database via ADO .NET or Entity Framework or LINQ to SQL. Maybe at another point in the application’s lifetime a new implementation would be dropped in that uses WCF web services instead.
The point in my above example is that the calling code won’t break. The interface is satisfied – only the behavior has been changed.