Self-documenting code is a myth

How many times did I heard that stupid talk? “Comments aren’t needed! Code should be self-documenting”. If you think this way, then… believe me or not, you’re wrong. Good developer does not need comments to describe, what he or she is doing. But there’s always a purpose for doing something, which must be documented for future reference. If you think, you can achieve the same with self-documenting code, you’re going strictly into violating fourth of Five major software development rules. Which says: “Premature optimization is the beginning of all hell!“.

And here is a good example. So, we have this piece of code:

var
    tTemp = '',
    dotTemp = '';

/**
 * We use a trick with temporary disabling title, if user is also 
 * using tooltip for this field. Our popover would share title used 
 * in that tooltip, which is rather unwanted effect, right?
 */
if($(field).attr('rel') == 'tooltip')
{
    tTemp = $(field).attr('title');
    dotTemp = $(field).attr('data-original-title');

    $(field).attr('title', '');
    $(field).attr('data-original-title', '');
}

OK, I agree. This comment is too long. We don’t need to write, that we’re temporarily disabling title, because code here is self-documenting and explains this correctly. But, what about the purpose? What any developer would really read out of this code (without comment)? That we’re disabling title, if user is also using tooltip. Great! Pity, that the most important part of message — “Our popover would share title used in that tooltip, which is rather unwanted effect” — is completely lost.

Can we get the same effect self-documenting code and drop the entire comment? Sure, we can! I know a guy, who would introduce here a function and would name it…

temporarilyRemoveTooltiTitleToAvoidConflictWithPopover()

Yes… the Old Wise Developers are always right… Premature optimization is the beginning of all hell…

Leave a Reply