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

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

    I follow a very simple rule with extension methods and helper classes.

    Anytime I have a method that could be relegated to a static helper class I will weigh the usefulness of it in a general scope, do I really want this method to be shared? Is the meaning clear and useful to others?

    If I can answer yes to this question I will create it to be an extension method. Where I have a shared library that among other things contains all of my Extension methods in 1 namespace with each class file defined as TypeNameExtension so it becomes very clear what to expect is inside that class so that you can easily locate the code.

    If I question the need for a helper method as a globally accessible usage I will declare the method private static and leave it inside the owning class.

提交回复
热议问题