Controls Enable Disable Refactoring

December 26th, 2009 | by | technology

Dec
26

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;
  }
}

When the same code can be expressed in a more clear and clean format:

bool isFindTextPresent = !String.IsNullOrEmpty(textBoxFind.Text);
bool isReplaceTextPresent = !String.IsNullOrEmpty(textBoxReplace.Text);
buttonFindNext.Enabled = isFindTextPresent;
buttonReplace.Enabled = (isFindTextPresent && isReplaceTextPresent);
buttonReplaceAll.Enabled = (isFindTextPresent && isReplaceTextPresent);

No Comments »

Arrowhead Antipattern

December 26th, 2009 | by | technology

Dec
26

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:

Sometimes, the Arrowhead Antipattern is not clearly visible, or the automated refactoring tools fails to do the refactoring, due to the else condition, etc.

if (listView.SelectedItems.Count > 0)
{
  ListViewItem item = listView.SelectedItems[0];
  if (item != null)
  {
    listView.Items.Remove(item);
  }
}
else
  MessageBox.Show(this, "Please select an item from the list to remove.");

But whenever you see some validation code and the Arrowhead Antipattern, it means, time to refactoring. Most the time, reversing the if condition will do the job, and the automated tools will now identify that piece of code as a candidate for refactoring Arrowhead Antipattern.

if (listView.SelectedItems.Count <= 0)
{
  MessageBox.Show(this, "Please select an item from the list to remove.");
  return;
}

ListViewItem item = listView.SelectedItems[0];
if (item == null)
  return;

listView.Items.Remove(item);

No Comments »

The power of refactoring?

December 24th, 2009 | by | technology

Dec
24

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;
}

The code doesn’t made any sense to me, so I refactored and guess what the outcome:

if (mShowShadow && DropShadowSupported())
  parameters.ClassStyle += CS_DROPSHADOW;

No Comments »