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

前端 未结 7 1981
慢半拍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:54

    The problem is that Extension methods aren't necessarily clear.

    When you see something like this in code:

     myObject.Foo();
    

    The natural instinct is that Foo() is a method defined on myObject's class, or a parent class of myObject's class.

    With Extension methods, that's just not true. The method could be defined nearly ANYWHERE, for nearly any type (you can define an extension method on System.Object, although it's a bad idea...). This really increases the maintenance cost of your code, since it reduces discoverability.

    Any time you add code that is non-obvious, or even reduces the "obviousness" of the implementation, there is a cost involved in terms of long term maintainability.

提交回复
热议问题