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
public void LoadSettings(){}
public void SaveSettings(){}

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
public void ExportConfigData(){}

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
void LoadSettings;
void SaveSettings;

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

<PRE>public class NamePrefs : Form, IPreferencesForm

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.

This entry was posted in c#. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

5 Responses to Working with Interfaces Part One – Contracts

  1. cramsay says:

    I’d really appreciate feedback (private & public) on this one guys!

  2. Jamal Hansen says:

    When I started learning object oriented programming I was enthralled by inheritence. I used it as much as I could, and often when I didn’t need to. Often I would put some behavior in the ancestor that I later found that I didn’t need in its descendants. Then I’d find myself overriding behavior, calling super and making a real mess of things. Interfaces can be a nice alternative in these situations. Allowing you to standardize certain aspects of behavior without going in for full blown inheritence.

  3. Good post Colin! It will make for good conversation.

    I am on the same path Colin. I have no degree, kind of stumbled into programming from web development and learned as I went, no mentor just myself reading books and asking for help in groups. As a result it took me awhile to fully leverage the power of interfaces. After using them for awhile now I don’t see how I got on without them.

    The best piece advice I can give everyone to help them with interfaces is first, the word “Contract”. It confused me alot at first but it made sense later because all the interface does is assure clients that said class can perform the interface operations.

    Then to the next step of once you know that a class can do a certain set of methods, you can then swap out classes that otherwise have no relation to each other. If they did, you could use inheritance.

    A prime example I just coded the other night. I had an interface called IAuthService. The interface has two methods:

    bool Authenticate(string username, string password);
    string[] GetGroupMembership(string username);

    Now, there are two classes that implement this interface,
    ActiveDirectoryAuthService : IAuthService
    DatabaseAuthService : IAuthService

    The consumer method would then be like so:
    class Consumer
    public void DoWork(IAuthService myAuthService)
    return myAuthService.Authenticate(“un”, “pw”);

    As you can see, I can now change the classes the consumer is using very easily, because the consumer doesn’t care how the task is achieved, it just wants the task to be done.

    Therein lies the power, loose coupling. Because no consumer knows about the intimate details of the AuthService class. Only how to interact with it.

    Hopefully thats not too confusing. An example like that really helped me to see the light with interfaces when I first started using them.

    Didn’t mean to hijack your thread colin, just wanted to let everyone know what helped me see the light.

    good post colin!

  4. cramsay says:

    No problem Sean, it can be a tricky topic initially so more examples are good!

    Jamal: I think your example is pretty much why C# disallows multiple inheritance. Imagine what sort of a mess you could get in then!

  5. I’ve used Model View Presenter in the last couple years for my Forms and it can become very hairy fast if you have “base” forms (inheritence). What interfaces allow you to do is ensure the contract is being fulfilled, but the other benefit is mocking. You are able to make your form implement IView for example and mock that and therefore unit test your UI. There are qwerks with doing that in ASP.NET, but the best (reading) example is in the “Agile Patterns, Patterns, and Practices in C#” book by Robert and Micah Martin, Chapter 38 shows the Model View Presenter in action. (beware, they refer to the UI as an interface also, so read carefully)

    Hope this helps.

    Great post Colin. I think interfaces can sometimes be hard to wrap your mind around. Once a person has that “aha” moment, they will never turn back.

    SIDE NOTE: The only thing a degree in our field, unfortunately, will do is get your foot in the door for an interview (usually). If you have a recruiter who actually reads the resumes and sees the the experience listed, everyone has a fighting chance.

    I personally don’t rate a developer on his education. I base it on experience.