Background: In the spirit of “program to an interface, not an implementation” and Haskell type classes, and as a coding experiment, I am thinking about what it would mean to create an API that is principally founded on the combination of interfaces and extension methods. I have two guidelines in mind:
-
Avoid class inheritance whenever possible. Interfaces should be implemented as
sealed classes.
(This is for two reasons: First, because subclassing raises some nasty questions about how to specify and enforce the base class’ contract in its derived classes. Second, and that’s the Haskell type class influence, polymorphism doesn’t require subclassing.) -
Avoid instance methods wherever possible. If it can be done with extension methods, these are preferred.
(This is intended to help keep the interfaces compact: Everything that can be done through a combination of other instance methods becomes an extension method. What remains in the interface is core functionality, and notably state-changing methods.)
Problem: I am having problems with the second guideline. Consider this:
interface IApple { }
static void Eat(this IApple apple)
{
Console.WriteLine("Yummy, that was good!");
}
interface IRottenApple : IApple { }
static void Eat(this IRottenApple apple)
{
Console.WriteLine("Eat it yourself, you disgusting human, you!");
}
sealed class RottenApple : IRottenApple { }
IApple apple = new RottenApple();
// API user might expect virtual dispatch to happen (as usual) when 'Eat' is called:
apple.Eat(); // ==> "Yummy, that was good!"
Obviously, for the expected outcome ("Eat it yourself…"), Eat ought to be a regular instance method.
Question: What would be a refined / more accurate guideline about the use of extension methods vs. (virtual) instance methods? When does the use of extension methods for “programming to an interface” go too far? In what cases are instance methods actually required?
I don’t know if there is any clear, general rule, so I am not expecting a perfect, universal answer. Any well-argued improvements to guideline (2) above are appreciated.
Your guideline is good enough as it is: it already says “wherever possible”. So the task is really to spell out the “wherever possible” bit in some more details.
I use this simple dichotomy: if the purpose of adding a method is to hide the differences among subclasses, use an extension method; if the purpose is to highlight the differences, use a virtual method.
Your
Eatmethod is an example of a method that introduce a difference among subclasses: the process of eating (or not) an apple depends on what kind of apple it is. Therefore, you should implement it as an instance method.An example of a method that tries to hide the differences would be
ThrowAway:If the process of throwing away an apple is the same regardless of the kind of the apple, the operation is a prime candidate for being implemented in an extension method.