Why the R# Method Group Refactoring is Evil
- by Liam McLennan
The refactoring I’m talking about is recommended by resharper when it sees a lambda that consists entirely of a method call that is passed the object that is the parameter to the lambda. Here is an example: public class IWishIWasAScriptingLanguage
{
public void SoIWouldntNeedAllThisJunk()
{
(new List<int> {1, 2, 3, 4}).Select(n => IsEven(n));
}
private bool IsEven(int number)
{
return number%2 == 0;
}
}
When resharper gets to n => IsEven(n) it underlines the lambda with a green squiggly telling me that the code can be replaced with a method group. If I apply the refactoring the code becomes:
public class IWishIWasAScriptingLanguage
{
public void SoIWouldntNeedAllThisJunk()
{
(new List<int> {1, 2, 3, 4}).Select(IsEven);
}
private bool IsEven(int number)
{
return number%2 == 0;
}
}
The method group syntax implies that the lambda’s parameter is the same as the IsEven method’s parameter. So a readable, explicit syntax has been replaced with an obfuscated, implicit syntax. That is why the method group refactoring is evil.