Sunday, December 03, 2006

The Inter - face

Interfaces in object oriented programming have been around for a few years now. I still run into people who do not use interfaces while programming.
For .net developers this might be because VS.NET does not have a menu for adding interfaces, and VS.Net allows you to be more or less ignorant towards the structure of the program you are making (Drag'n'Drop coding I think I would call it :)).

To me structure is the most important thing in software development. Interfaces is a cornerstone in building this structure.

Interfaces are great when you need to consume objects, and you are more conserned with its use than what it is.
Interfaces come into play when you want to create reusable code. Directly copying source code is not a good solution and I prefer structuring my way out of it. Making a component or a framework if you like.
If you can avoid it keep your reusable components working without the user having to extend a series of classes of yours. The user might have reasons not to extend your classes, such as the need to extend other classes. Maybe the objects need to be serialized in between calls or some thing else. If you force the user to extend your classes, you must be sure the user can do anything to it in another context.

There is of course nothing wrong with providing a default implementation for your interfaces. Please don't give these default implementation the name that fits the use of the interface. IList and List is a bad example of naming a default implementation, or maybe it's more that IList should not have a default implementation. Because of these bad names, I dislike prefixing interfaces with I. The interface is the main thing and should be given the real name. Normally there is no need for a default implementation, but if needed I like giving the default implementation a Impl postfix far better.

When you design your system, you must think interfaces to begin with. There is little benefit from designing a system using classes, adding interfaces to all classes afterwards. Interfaces are only relevant if they actually respresent some decoupling in your system.

As a class can implement as many interfaces as you like, interfaces can be very small. This means that by using interfaces you code will only require the functionality it actually uses.. and the people using your product will only have to implement what is needed. They do not have to extend an existing class and thereby enherit a lot of useless functionality.

Less is more!
Interface > Class