开发者

should i use extension method or member method in this case?

for example,

        class Aclass
        {
            void method1()
            { 
               int[] a = new int[5]{1,2,3,4,5};
               var b = a.Accumulated().ToArray(); // 开发者_C百科so that b = {1,3,6,10,15}
            }
        }

Currently Accumulated() is an extension method. However an equivalent approach I reckon is to define a private member method in Aclass so that MakeAccumulated(a).ToArray() gives {1,3,6,10,15}.

What is a good practice?


Aclass is a place for methods which make logical sense for Aclass objects; best practice is to not use it as a general store for helper functions. A good rule of thumb is that if a method never references member variables then it might be out of place in the class.

A function on int arrays probably has no place in Aclass. I'd put it in an extension method.


it's not a question of good practice but of preference. both are valid options. if you need the method only in instances of Aclass then I'd limit it to a class method, that's also more obvious to others inspecting the class.


I would choose the member function approach, cause extensions methods, I personally, choose for something I'm not able to extend, or have a problem to extend to (complexity, not mine code, serialization issues, whatever...). In your case, you have a class written by you, so just extend it, by following clear OOP design.

For extension methods, you need to define another class, for someone who is not very familiar with your code, or for you after 2 years, will be not very clear why it's done in that way.

Regards.


If .Accumulated() is only going to be called from instances of Aclass, make it a member of the class. It wouldn't be practical to have an application-wide extension method for int[] (or Ienumerable as someone else pointed out) if it's only used within an instance of one class. Keep in mind that extension methods are just for added extensibility.

public static string Hello(this string Value) { return Value + "Hello"; }

string s = "Hello".Hello();

...is the same as:

public static string Hello(string Value) { return Value + "Hello"; }

string s = Utilities.Hello("Hello");

Would you put .Hello() in a utility class if you're only going to use it within the instance of another class? If you use .Accumulated() elsewhere in the application, though, an extension method would work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜