views:

69

answers:

3

What is the general thinking on the use of extension methods that serve no purpose other than enhancing readability?

Without using extension methods we might have the method

IEnumerable<DependencyObject> GetDescendents(DependencyObject root) {}

that could be called with

var descendents = GetDescendents(someControl);

or

foreach (var descendent in GetDescendents(someControl)) {}

Although there's nothing wrong with this I find the instance.method() notation to be more readable so I might consider making this an extension method with this signature

public IEnumerable<DependencyObject> GetDescendents(this DependencyObject root) {}

allowing it to be called with

var descendents = someControl.GetDescendents();

or

foreach (var descendent in someControl.GetDescendents()) {}

So my question is whether you think this is reasonable or an abuse of extension methods. If it was simply a matter of declaring the function differently I wouldn't hesitate; but the fact that using an extension method requires it be coded in a different, static class makes me wonder if it's worth the effort or not. The example I'm using above is a fairly generic one and might have merit as an extension method that will be used in several places but often this is not the case and I would be coding the static class containing the extension in the same file as the single class that uses it.

+2  A: 

Most if not all extension methods fall into this category to some degree, since they can't operate on the internals of a class anymore than your static function. At any rate, any extension method can be rewritten in a static class with an extra parameter representing the object (arguably, that's exactly what an extension method is anyway).

To me, it's entirely a question of style: in the example you provided, I'd probably jump for the extension method. I think the important question here is, Is this function something I'd write as part of the class if I were to reimplement the class, and does it make sense as such? If yes, then go for it, if no, then consider a different solution.

Matthew Scharley
+1  A: 

An extension method only exists to improve readability - it is merely a syntax shortcut that allows you, by specifying the this keyword on the first argument, allows you to call the method on the object instance in question. So I think it is entirely reasonable.

David M
+2  A: 

I think the big advantage of extension methods is discoverability. If someone is unaware that one of their team members created a GetDescendents method in a utility class somewhere, they'll never use it. However, if that method starts to show up in Intellisense or in the Object Browser, there's a decent chance they will stumble across it. If you start to make more extensive use of extension methods, people will start to use the tools I mentioned to look for extensions that add value.

Rob Windsor
I never thought of this aspect. It makes a lot of sense.
Steve Crane