Another common Anti-pattern is the Arrowhead Antipattern. Refactoring away from the arrowhead antipattern is as simple as swapping the conditionals, i.e. flatten conditionals statements, to leave the method as soon as possible. It is so common and so much have been written about it, I thought to just copy the links:
Refactoring
Controls Enable Disable Refactoring
How many times we have written such code to enable/disable controls, based on some conditions:
if (string.IsNullOrEmpty(textBoxFind.Text))
{
buttonFindNext.Enabled = false;
buttonReplace.Enabled = false;
buttonReplaceAll.Enabled = false;
}
else
{
buttonFindNext.Enabled = true;
if (string.IsNullOrEmpty(textBoxReplace.Text))
{
buttonReplace.Enabled = false;
buttonReplaceAll.Enabled = false;
}
else
{
buttonReplace.Enabled = true;
buttonReplaceAll.Enabled = true;
}
}
{
buttonFindNext.Enabled = false;
buttonReplace.Enabled = false;
buttonReplaceAll.Enabled = false;
}
else
{
buttonFindNext.Enabled = true;
if (string.IsNullOrEmpty(textBoxReplace.Text))
{
buttonReplace.Enabled = false;
buttonReplaceAll.Enabled = false;
}
else
{
buttonReplace.Enabled = true;
buttonReplaceAll.Enabled = true;
}
}
The power of refactoring?
Check out this piece of code taken from CodeProject.
bool son;
if (mShowShadow == false)
son = false;
else
{
if (DropShadowSupported() == false)
son = false;
else
{
son = true;
}
}
if (son)
{
parameters.ClassStyle += CS_DROPSHADOW;
}
if (mShowShadow == false)
son = false;
else
{
if (DropShadowSupported() == false)
son = false;
else
{
son = true;
}
}
if (son)
{
parameters.ClassStyle += CS_DROPSHADOW;
}
The code doesn't made any sense to me, so I refactored and guess what the outcome:
if (mShowShadow && DropShadowSupported())