The excellent developer and my former schoolmate
Bent André Solheim just posted this
great blogpost about two of my favorite refactoring techniques: Guard Clauses and Composed Methods. This is stuff that I can really recommend using. I've been using these techniques for a while and they really do make your code easy to read and maintain, and it has less bugs because of it.
I think the refactoring I use the most when working on legacy code is Rename. Proper naming of variables, methods and classes are the number one most important readability aid. Having lots of needless hungarian notation, abbreviations, or names that just mean nothing, adds noise and obfuscation.
Second must be grouping together related blocks of logic within long methods and then using Extract Method to work towards Composed Methods. I often end up restructuring a lot before I can extract the methods because the code is tangled up in itself, like reuse of local variables (please, don't do that, and don't declare everything at the top of the method).
Then it's reducing the levels of nesting by using Guard Clauses. And extracting methods often go hand in hand with this. If you have an if-statement and then a block of code after it that is to be executed regardless, then you can't make a guard that returns early from that method.
public void DoWork(string a, string b)
{
// Handle the DoStuff first
if (a != null && b != null)
{
if (a.StartsWith(b))
{
DoStuff(a, b);
}
}
DoImportantThing();
}
This if-statement can't be made a gaurd clause like it stands. But extracting that block to a method of its own cleans that up:
public void DoWork(string a, string b)
{
HandleStuff(a, b);
DoImportantThing();
}
private void HandleStuff(string a, string b)
{
if (a == null || b == null)
return;
if (!a.StartsWith(b))
return;
DoStuff(a, b);
}