Wednesday, June 15, 2011

Extension methods strike back

In my previous post I showed how static utility functions that extend base library functionality can be rewritten using extension methods. Now I will explain why I don't think it is a good idea to do so.

Extension methods were added primarily to allow LINQ functionality to extend base level classes without changing the spec of the base classes. You can see this in action by adding a reference to the System.Linq namespace to your code and suddenly arrays have methods like OrderBy in the intellisense list.

This is great for Microsoft which can co-ordinate between the Linq and core library teams but what happens when an extension method you've written conflicts with a change in the base library. Well this is documented here, you lose:
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.
For example, say you create an extension method named WordCount that looks for spaces to count words. Then in a new .NET release Microsoft also adds a WordCount method to the String class but their version counts hyphenated words as separate words. Your application may suddenly change its output or crash. Even good unit tests may not catch all of the edge cases.

Granted there is probably a remote chance of this happening and you could safety against it by prefixing all of your extension methods with something non-standard. However I just don't feel there is enough gain to be had with using extension methods over static utility classes.

No comments: