What is the motivation behind “Use Extension Methods Sparingly?”

前端 未结 7 1832
慢半拍i
慢半拍i 2021-02-05 23:38

I find them a very natural way to extend existing classes, especially when you just need to \"spot-weld\" some functionality onto an existing class.

Microsoft says, \"In

7条回答
  •  攒了一身酷
    2021-02-05 23:55

    I have a growing library of extension methods that operate on BCL classes for simplifying common problems, that look confusing at first glance. Frankly, I think Extension Methods make things a lot more readable. For instance, take an if statement testing to see if a number is between two numbers:

    if (x <= right && x >= left )
    {
       // Do Something
    }
    

    What if right is less than left on accident? And exactly what does that do? When the variables are simply like x and left, then its easy to undertand. But what if they are properties on a long class? The if statement can get pretty big, which obfuscates the rather simple thing you are trying to do.

    So I wrote this:

    public static bool Between(this T test, T minValue, T maxValue)
        where T : IComparable
    {
        // If minValue is greater than maxValue, simply reverse the comparision.
        if (minValue.CompareTo(maxValue) == 1)
            return (test.CompareTo(maxValue) >= 0 && test.CompareTo(minValue) <= 0);
        else
            return (test.CompareTo(minValue) >= 0 && test.CompareTo(maxValue) <= 0);
    }
    

    Now I can improve my if statement into this:

    if (x.Between(left, right))
    {
       // Do Something
    }
    

    Is this "extraordinary"? I don't think so... but I do think it's a significant improvement on readability, and it allows some extra checking on the test inputs for safety.

    The danger I think Microsoft wants to avoid here is people writing a ton of Extension Methods that redefine Equals and ToString.

提交回复
热议问题