Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Add semantic through your code, not through commenting

2 min read

Is it good to have a lot of code comments, explaining things s.t. your other team members know what was your intention when writing certain pieces?? Well, not fully. Having a lot of code comments throughout your code is also considered to be a code smell and should therefore be avoided. But so, what should be done? Just remove the comments? No, the key part is to add semantic by writing explicit, well readable code.

One way (of many such as writing meaningful variable names) of adding semantic to your code is in my eyes tightly related to the "Extract Method" refactoring. I'd like to mention it here shortly with a real example because I think people should care about this and apply it (where appropriate of course).

The method below shows a "real" code sample, where a comment has been added for explaining the purpose of the following lines of code.

if (someConditionHolds)
{
//formats the date according to the given culture
DateTime date;
if (DateTime.TryParse(textBoxDate.Text, new CultureInfo(this.PreviousCulture), DateTimeStyles.AssumeLocal, out date))
{
textBoxDate.Text = date.ToString(this.DisplayFormat, Thread.CurrentThread.CurrentUICulture);
}
}
This code looks quite complex, you see the reading of the culture from the current thread, then there is some other code involved which is creating a new culture object based on the previously used culture etc...Basically a lot of complex stuff which I don't want to bother about if I was not the developer who wrote this piece. So one would read the comment above and understand, ok, these lines are just formatting the date according to the current culture and assigning it to the textbox.

In such a case Fowler suggests to apply the "Extract Method" refactoring and restructure it as follows
if (someConditionHolds)
{
textBoxDate.Text = GetCultureFormattedDateString(textBoxDate.Text);
}

private string GetCultureFormattedDateString(string toFormat)
{
string result = toFormat;

DateTime date;
if (DateTime.TryParse(textBoxDate.Text, new CultureInfo(this.PreviousCulture), DateTimeStyles.AssumeLocal, out date))
{
result = date.ToString(this.DisplayFormat, Thread.CurrentThread.CurrentUICulture);
}

return result;
}
Now this really looks simple, doesn't it? When I read over the code, I come across the method call and I immediately catch what is going on by reading the method name. Then, if I'm interested in this special thing, I can go and read the complex implementation, but otherwise I just don't care and go on.
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus