10/20/2006

A Note About C# and Interfaces

Interfaces seems to be one of the biggest conceptual problem areas for beginning developers. Some people just have difficulty understanding what an Interface really is, but more often, developers can understand what it is; it's just that they have difficulty getting a grasp on "what it is for".

Recently on the C# MS Group there was a post that basically revolved around the concept of "why do I need interfaces" vs. Multiple Inheritance and so on. There were two very good responses, one, a real "gem", by Marina Levit, an MVP who has a penchant for succinct and highly detailed instructional replies on the newsgroups, and another by "DeveloperX" - an unnamed but equally proficient poster. I reproduce them here:

Levit:

Interfaces are meant for classes that have the same behavior, but different
implementation for that behavior.

For example, a Person object might implement a Move method one way - by
walking.

A Car object might implement a Move method another way - by driving.

However, a Person and a Car, have nothing else in common. They can't share a
common ancestor.

But they can both implement the same interface. And someone with a
collection of objects implementing this interface, can call the Move method
on each of them, without regard as to whether the object is a Car, a Person,
or something else. Because they all implement the same interface, they can
all be moved.

An interface is not a blueprint for a class. If you have only one class
implementing the interface, then you shouldn't have an interface. And if
you have multiple classes implement the interface, but they all have the
same implementation, then you should be using inheritence.

DeveloperX:

Interfaces also allow you to group areas of functionality which makes
developing simpler.

For example imagine a wheel object representing a wheel with a tyre on
it. You might expect to see methods and properties like , width,
height, tread pattern, spoke style, valve, inflate, polish, deflate,
tyremake, hubmake, tyremanufacturer, hubmanufacturer.

Now when you're programming against that wheel you're going to see a
huge list of properties and it might not be immediately clear what they
do.

Now have a wheel object that implements IHub and ITyre things become
clearer. you know IHub.polish will polish the hub, previously you might
have inadvertantly polished the tyre. You can also now remove
tyremanufacturer and hubmanufacturer and simply have manufacturer on
each of the interfaces.