Skip to main content

Rule #27: If it takes up space in more than one place, give it a home of its own!

Refactoring some code, I came across this construct:

if (gridTextBox.Text != " New Country")
{
 country.CountryId = gridTextBox.Text.Trim();
}
else
{
 country.CountryId = gridTextBox.Text;
}
CountryId was the key field for the item; this really old code was making sure that when it created a new item, it would call it " New Country" 
with a single space in the front, but any other entry would end up being trimmed of whitespace on both ends.


And then later on in the same method was:
if (e.Item.Cells[5].Text != " New Country")
{
 country.OldCountryId = e.Item.Cells[5].Text.Trim();
}
else
{
 country.OldCountryId = e.Item.Cells[5].Text;
Same thing, different source, different destination! Immediately says 'relocate me!' in my mind!
So we end up with:
country.CountryId = GetCountryName(gridTextBox.Text);
and
private string GetCountryName(string source)
{
 string result = source.Trim();
 
 if (source.Equals(" New Country"))
 {
  result = source;
 }
 
 return result;
}
'Get' probably isn't the proper verb here, but the takeaway is converting repetitive code to a verb/noun function/method/call that centralizes the usage.

Comments