Working with Interfaces Part One – Contracts


I hold my hands up – I am a programmer who doesn’t have a computer science background. My education only skimmed programming and was totally bereft of any architectural considerations. I almost stumbled into my first programming job, and I such I realise I have a lot of to learn about that which I use to earn a crust.

One of the things that took me a while to appreciate was the power of interfaces. I specifically remember a conversation I had with my boss in which I said, baffled, “so… they don’t actually *do* anything then??”. And this is kind of true, interfaces don’t really “do” anything. Instead, they’re an enabler for a couple of really useful techniques.

Imagine you’re creating a series of sub forms in a Windows application. They’re each supposed to do a similar thing and should always have methods to LoadSettings and SaveSettings. Something like this:

<PRE>public class NamePrefs : Form<br /> {<br /> public void LoadSettings(){}<br /> public void SaveSettings(){}<br /> }</PRE>

However, a new developer jumps in to your project and is instructed to create a new preferences form. They come up with something like this:

<PRE>public class HeightPrefs : Form<br /> {<br /> public void ExportConfigData(){}<br /> }</PRE>

For starters they’ve forgotten that the form needs to load up existing data and so hasn’t implemented loading functionality. Secondly, they’ve called their save method something different to the save method in all your other preference forms. Interfaces can provide a possible solution:

<PRE>public interface IPreferencesForm<br /> {<br /> void LoadSettings;<br /> void SaveSettings;<br /> }</PRE>

This interface is specifying a contract which implementing classes can adhere. Our initial example would look like:

<PRE>public class NamePrefs : Form, IPreferencesForm<br /> {<br /> &#8230;.<br /> }</PRE>

If our second example also inherited from IPreferencesForm, that implementation would throw compiler errors as neither the LoadSettings or SaveSettings methods specified in the interface contract are present in the HeightPrefs class.

Using interfaces only solves one part of the problem – you’ve got to make sure that people do actually inherit from them. That’s an issue which can be solved by enforcing developer policies, or technically, by ensuring only classes which implement the correct interface will get loaded by your main program. However, when interfaces are used in this manner, they can improve consistancy and lead to improved discoverability in your code.

Coding C# in Style