Extension Method Patterns

Extension Method Patterns

One of the walls I hit the most in C# when designing classes is the lack of support for multiple inheritance, which makes that one spot for inheriting from a very valuable spot indeed. For the purposes of this discussion, we’ll start with a simple implementation of the specification pattern :

public interface ISpecification<T> {
   bool IsSatisfiedBy(T item);
}

The evaluation is all set, but now we feel the need to add the boolean operators And, Or, and Not. Most developers follow the route of changing the interface to add And, Or and Not, create a base (abstract) class (let call it SpecificationBase) implementing the operators and leaving the IsSatisfiedBy method abstract. The downside of this approach is that concrete implementations of specifications are forced to give up their one empty slot for inheritance. An alternative is to leave the interface as is, and implement extension methods that operate on the interface - no inheritance needed.

public static ISpecification<T> And<T> (this ISpecification<T> left, ISpecification<T> right) {
   return new AndSpecification<T>(left, right);
}

The downside with this implementation is that you need to import the namespace in order use the methods. Although most people will probably do this automatically anyway, it might not be clear what operations the class has to offer.

My question is this : In the context of a reusable class library like NGenerics, is using extension methods in this way evil?

Photo by Kyle Glenn on Unsplash


See also