Friday, March 30, 2012

Comment: Yet another code smell

Today we are going to take a look, and discuss on yet another code smell named “Comment”. Sounds like some thing is been told wrong, yes you guys heard right, comment is one kind of smell. The days of well documented code with comment are gone, now time has changed and new agile wind is flowing, as a result comments are now considered as code smell.

How Comment is smell?

Who would have thought that this day will ever come, I have worked with organizations where the developers is been given extra time to put right comment on code, but its history. How comment is smell? its simple the code is not self explanatory, so the code is smelly.

“The idea is to make each and every piece of code self explanatory.”

If your code need comment, you should take careful consideration to refactor your code so that it need no comment at all.

Some Useful Example

In bellow code what ever comment you are seeing is a comment smell.

/// <summary>
/// this method gets a tag or a country
/// </summary>
/// <param name="countryName"></param>
/// <returns></returns>
public static string GetTag(string countryName)
{
//loop through the dictionary key
foreach (string tag in _dictionary.Keys)
{
//search the key
List<string> patternList = _dictionary[tag];
bool found = false;

//if the tag is found return it
found = IsFound(countryName, null, patternList);

if (found)
{
return tag;
}
}
return string.Empty;
}
/// <summary>
///
/// </summary>
/// <param name="title"></param>
/// <param name="description"></param>
/// <param name="patternList"></param>
/// <returns></returns>
private static bool IsFound(string title, string description,
IEnumerable<string> patternList)
{
//traverse in pattern list
foreach (string pattern in patternList)
{
//get rid of . and /.
string searchPattern = pattern.Replace(".", "/.");
string sourceContent = title;
//use regex to find the tag match
bool found = Regex.IsMatch(sourceContent, searchPattern, RegexOptions.IgnoreCase);

if (!found && !string.IsNullOrWhiteSpace(description))
{
sourceContent = description;
found = Regex.IsMatch(sourceContent, searchPattern);
}
if (found)
{
return true;
}
}

return false;
}



Which comment is Allowed?



  • In a function a algorithm is been implemented, for instance a tax calculation procedure, and the procedure is been implemented following a particular rule in a tax book. If you provide the name and reference of the book its not a comment.
  • Class responsibility declaration, its okay to put few lines of comment above a class, and describe its purpose.

Its all about judgment


In the end a programmers judgment matters, we would know when to comment and where not to comment, with little refactor effort we can avoid comment.

No comments:

Post a Comment