“Program to an interface” using extension methods: When does it go too far?

天大地大妈咪最大 提交于 2019-12-12 07:58:32

问题


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.


回答1:


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.




回答2:


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.




回答3:


I've noticed that C# extension methods can be quite similar to C++ non-member non-friend functions in the following way: Both Scott Meyers and Herb Sutter claim that in C++, encapsulation is sometimes increased by not making a function a class member:

"Where possible, prefer writing functions as nonmember nonfriends." — Summary of Herb Sutter's GotW #84

(Sutter justifies this approach in his article about the Interface Principle.)

Back in 1991, Scott Meyers even formulated an algorithm for deciding whether a function should be a member function, a friend function, or a non-member non-friend function:

if (f needs to be virtual)
  make f a member function of C;
else if (f is operator>> or operator<<)
  make f a non-member function;
  if (f needs access to non-public members of C)
    make f a friend of C;
else if (f needs type conversions on its left-most argument)
  make f a non-member function;
  if (f needs access to non-public members of C)
    make f a friend of C;
else if (f can be implemented via C's public interface)
  make f a non-member function;
else
  make f a member function of C;

— Scott Meyers expanded algorithm from 1998 (reformatted)

Some of it is obviously specific to C++, but it should be fairly easy to find an analogous algorithm for the C# language. (As a start, friend can be approximated in C# with internal access modifier; "non-member functions" can be either extension methods or other static methods.)

What that algorithm doesn't say is when, or why, f "needs to be virtual". @dasblinkenlight's answer goes quite some way towards explaining that bit.


Relevant questions on Stack Overflow:

  • Large scale usage of Meyer's advice to prefer non-member, non-friend functions?

  • When should functions be member functions?



来源:https://stackoverflow.com/questions/11441905/program-to-an-interface-using-extension-methods-when-does-it-go-too-far

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!