7

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:

  1. 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.)

  2. 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.

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
  • I think a better place to start would be `IEnumerable` rather than a contrived example. – ChaosPandion Jul 11 '12 at 21:42
  • well, you've *kindof* violated rule #1 by making `IRottenApple` extend `IApple`... (although there it just states *class* inheritance) – John Gardner Jul 11 '12 at 21:43
  • @John: I don't think so. I believe that *interface* inheritance avoids many of the issues of subclassing. (For example: Does an overridden method have to be called from the derived class or not? That question simply vanishes when you disallow subclassing.) – stakx - no longer contributing Jul 11 '12 at 21:50

2 Answers2

6

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 Eat method 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:

public static void ThrowAway(this IApple apple) {
    var theBin = RecycleBins.FindCompostBin();
    if (theBin != null) {
        theBin.Accept(apple);
        return;
    }
    apple.CutUp();
    RecycleBins.FindGarbage().Accept(apple);
}

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • +1. For hide vs. highlight distinction. Side note I think you should say "use an interface method." instead of "use a virtual method." – Alexei Levenkov Jul 11 '12 at 22:12
  • +1 and :-D. But isn't it the very purpose of abstraction through polymorphism to make different implementations *outwardly* appear the same? That is, doesn't proper abstraction *always* encourage difference-hiding methods such as `ThrowAway`? – stakx - no longer contributing Jul 11 '12 at 22:22
  • Regarding my previous comment: The last paragraph of your answer provides a good guideline to distinguish your two cases. I mentioned _"different implementations"_ in the above comment, while you're giving an example where the implementation would always be the same. Thanks for a great answer. – stakx - no longer contributing Jul 11 '12 at 23:14
1

For me the expected output was correct. You type-casted (probably using that wrong) the variable to as an IApple.

For example:

IApple apple = new RottenApple();
apple.Eat();  // "Yummy, that was good!"
IRottenApple apple2 = new RottenApple();
apple2.Eat(); // "Eat it yourself, you disgusting human, you!"
var apple3 = new RottenApple();
apple.Eat();  // "Eat it yourself, you disgusting human, you!"

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 to far? In what cases are instance methods actually required?

Just my personal opinion when developing application:

I use instance methods when I'm writing something that I may or someone else may consume. This is because it is a requirement for what the type actually is. Consider an interface/class FlyingObject with a method Fly(). That is a basic fundamental method of a flying object. Creating an extension method really doesn't make sense.

I use (a lot) of Extension methods, but these are never a requirement for the use of the class they extend. For example, I have extension method on int that creates a SqlParameter (additionally it is internal). Still it makes no sense to have that method as part of the base class of int, it really has nothing to do with what an int is or does. The extension method is visually nice way of creating a reusable method that consumes a class/struct.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • What worries me about my example is that the code suggests `apple.Eat` will print a complaint, because that's what would happen in the (usual) case of virtual dispatch; yet, as you correctly state, extension methods don't work that way. -- Let's assume that eating an apple is *not* a fundamental operation of the `IApple` type, and that `Eat` is thus rightly implemented as an extension method. But then what is wrong with my guideline (2)? Why did it lead me into such an unexpected situation? How would I have to adapt it so that I'd detect & prevent these *before* someone runs into it? – stakx - no longer contributing Jul 11 '12 at 22:49
  • What if the Apple and RottenApple were together in a Basket ? They'd both be yummy! – Amy B Jul 13 '12 at 18:09
  • @stakx I think it's just a fundamental understanding that extension methods are really just static methods. Thus when the compiler attempts to search for a method signature, it will locate the one the matches as closely to the type as possible. `IRottenApple` is a closer match than `IApple` thus it the methods that use `IRottenApple` will be used over `IApple`. – Erik Philips Jul 13 '12 at 20:01
  • @David B: Exactly that is my issue. @Erik: Your explanation seems incorrect to me. The compiler makes its choice of the extension method to be called simply by looking at the static (compile-time) type of the variable that contains the `this` object. If that variable is declared as `IApple`, the compiler will *never* consider extension methods defined for more derived types (but possibly vice versa). – stakx - no longer contributing Jul 13 '12 at 20:08