Sunday, February 16, 2014

Refactoring is awesome

Today my goal is to read the whole C# book (Programming C# 4.0), in skimming fashion.  I'll miss a lot - but occasionally little nuggets have a way of jumping out.

One of those nuggets is refactoring.

So... sometimes I'm a coding slob.  It's really very embarrassing.  It almost feels like the stack I have in my brain is full, and so I'm not willing to add yet another layer of function calls into the method I'm currently writing, so I wind up with code that looks like this:

void frankslongmethod()
{
    doAction1a();
    doAction1b();
    doAction1c();

    doAction2a();
    doAction2b();
    doAction2c();
}

And you can easily imagine this growing into a hideous monstrosity very quickly.

*** It turns out that Visual Studio and Monodevelop have automated creating functions (and this step is called "refactoring").  You can conveniently select lines of code and right click "refactor" and it will bring up a dialog that lets you name the new function it will generate for you. ***


Afterwards, the code can look like this (depending on what code I selected and how I chose to name it):

void frankslongmethod()
{
   doAction1();

   doAction2();
}

void doAction1()
{
    doAction1a();
    doAction1b();
    doAction1c();
}

void doAction2()
{
    doAction2a();
    doAction2b();
    doAction2c();
}

It's also very slick - the automation process can figure out what arguments need to be passed to the generated functions.  Well worth trying out for yourself.

The beauty of it - my brain stack didn't need to be enlarged.  I just have to take this extra step of cleaning up my code with a refactoring step after I've finished my "write this algorithm as fast as you can" phase.

[And of course we can discuss this is taking an extra call - but that might even be handled by the compiler at run-time, so no worries for now.  If you're hitting that wall, it's a problem that can be addressed - the more serious problem is reducing cognitive load on new programmers trying to understand what the code does.]