Extension Methods vs Static Utility Class [closed]

霸气de小男生 提交于 2019-11-27 18:20:34

I would say that a pro is that it blurs the lines between what is in the framework and what isn't: you can use your own code as naturally as framework code, operating on framework types.

Extension methods shouldn't be used arbitrarily, of course - it's not like all static methods should become extension methods.

I try to think of it as whether the method is logically operating "on" its first parameter. Would it make sense as an instance method, if you were able to include it as an instance method?

A "con" which you may not be aware of: if the extended type later adds an instance method of the same name which is applicable with the same parameters, your calling code will transparently start calling that instance method next time you recompile. For example, Stream gained CopyTo in .NET 4... I'd previously written a CopyTo extension method, which then wouldn't be called. There's no warning that this is occurring, so you have to be on your guard.

One caveat: extension methods haven't been around for long enough for best practices to really become established. You should weigh up all opinions (even - or perhaps especially - my own ones) carefully.

At the end of the day, both approaches use static methods. The only difference between

string foo = "bob";
StringUtils.DoSomething(foo);

and

string foo = "bob";
foo.DoSomething();

is syntactic sugar. It boils down to personal preference and coding standards. Sometimes the method name can be descriptive enough to not warrant seeing the static class name. Other times it makes more sense to include the class name.

Finally, extension methods can be invoked as static methods too!

string foo = "bob";
StringExtensions.DoSomething(foo);

The above uses the same code as in the second example, but is invoked differently. With this last tidbit in mind, you could really create static utility classes as extension methods and then invoke them however you wish.

I personally like readabilty and chain calls(implicitly provides readability) that is provided by Extension methods.

 1) Readability:  
     bool empty = String.IsNullOrEmpty (myString)
     //in comparison to
     bool empty = myString.IsNullOrEmpty ();

 2) Chain calls:  
    var query = Enumerable.Range(0, 10)
                         .Where(x => x % 2 == 0)
                         .Reverse();
    //instead of
    var query = Enumerable.Reverse(Enumerable.Where(Enumerable.Range(0, 10), x => x % 2 == 0));

Con is your extension method can be overriden by instance member if you accidentally do it. Personally I dont like this. At least compiler should have screamed, if it is happening with in the same assembly.

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