Interfaces with static methods, reducing the cost of extensibility

Someone last week mentioned that Java was now getting static methods defined on interfaces. We’ve had that capacity, through extension methods, since C#3, and is one pattern I keep on reusing.

An interface, at core, is a contract of extensibility between me and other developers: Implement method Bla() and I promise you will be called whenever that stuff is needed. The problem with such an approach is that some functionality is repetitive and makes implementing the interface more complicated.

Let’s take the example of an interface that’s part of OpenRasta

public interface IDependencyResolver
{
T Resolve<T>();
object Resolve(Type serviceType);
}

Because both generic and non-generic methods are needed by the consumer, your initial reaction is to impose the implementation burden on the person implementing the interface.

Using static methods, we can take all that work away, and provide overloads and added funcitonality on any implementation of an interface. And it’s as simple as doing the following.

public interface IDependencyResolver
{
object Resolve(Type serviceType);
}
public static class DependencyResolverExtensions
{
public static T Resolve<T>(this IDependencyResolver resolver)
{
return (T)resolver.Resolve(typeof(T));
}
}

I now do most of the work, and the people wanting to implement the interface only have one method to implement. And everyone is happier.

Ads

Comment