Refactoring for dummies
I was recently looking at a web-cast and it was not related to refactoring at all, but the presenter said something about refactoring that just blew my mind. The code he started with looked something like this:
public ClassD GetD()
{
ClassA a = new ClassA();
ClassB b = a.GetB();
ClassC c = b.GetC();
ClassD d = c.GetD();
return d;
}
He then had the nerve to refactor for better performance into this:
public ClassD GetD()
{
return (new ClassA()).GetB().GetC().GetD();
}
The only thing he did was make the code harder to read. If you use a disassembler like this one to actually look at the generated code. And yes there is a difference in the number of lines of IL that is generated but I feel confident enough that those differences will be removed when the code is compiled to native code before execution. So the only thing accomplished by this refactoring is that the code is harder to read (original example had much longer method names) and the possibility to say "look how easy this is to use, it's only a single line of code". hate to break this to you but I can write anything and everything on a single line if that is important for you. But that doesn't make it better.
Don't refactor for performance unless you know you have a performance issue. Don't refactor to get fewer lines of code. Refactor to remove duplicate code and to make the code easier to understand, not making it harder to understand.