5 Best Practices for Commenting Your Code
Join the DZone community and get the full member experience.
Join For Freeone of the first things you learn to do incorrectly as a programmer is commenting your code. my experience with student and recently graduated programmers tells me that college is a really good place to learn really bad code commenting techniques. this is just one of those areas where in-theory and in-practice don’t align well.
there are two factors working against you learning good commenting technique in college.
- unlike the real world, you do a lot of small one-off projects as a solo developer. there’s no one out there fantasizing about dropping a boulder on you for making them decipher your coding atrocity.
- that commenting style you are emulating from your textbook is only a good practice when the comments are intended for a student learning to program. it is downright annoying to professional programmers.
these tips are primarily intended for upstart programmers who are transitioning into the real world of programming, and hopefully will prevent a few from looking quite so n00bish during their first code review. code review? oh yeah, that’s something else they didn’t teach you in school, but that’s a whole other article, i’ll defer to jason cohen on that one.
so let’s get started…
(1) comments are not subtitles
it’s easy to project your own worldview that code is a foreign language understood only by computers, and that you are doing the reader a service by explaining what each line does in some form of human language. or perhaps you are doing it for the benefit of that non-programmer manager who will certainly want to read your code (spoiler: he won’t).
look, in the not too distant future, you will be able to read code almost as easily as your native language, and everyone else who will even glance at it almost certainly already can. by then you will realize how silly it is to write comments like these:
// loop through all bananas in the bunch foreach(banana b in bunch) { monkey.eat(b); //make the monkey eat one banana }
you may have been taught to program by first writing pseudo-code comments then writing the real code into that wire-frame. this is a perfectly reasonable approach for a novice programmer. just be sure to replace the comments with the code , and don’t leave them in there.
computer: enemy is matching velocity.
gwen demarco: the enemy is matching velocity!
sir alexander dane: we heard it the first time!
gwen demarco: gosh, i’m doing it. i’m repeating the darn computer!
exceptions:
- code examples used to teach a concept or new programming language.
- programming languages that aren’t remotely human readable (assembly, perl)
(2) comments are not an art project
this is a bad habit propagated by code samples in programing books and open source copyright notices that are desperate to make you pay attention to them.
/* _ _ _ _ _ _ _ _ _ _ _ _ (c).-.(c) (c).-.(c) (c).-.(c) (c).-.(c) (c).-.(c) (c).-.(c) / ._. \ / ._. \ / ._. \ / ._. \ / ._. \ / ._. \ __\( y )/__ __\( y )/__ __\( y )/__ __\( y )/__ __\( y )/__ __\( y )/__ (_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._) || m || || o || || n || || k || || e || || y || _.' `-' '._ _.' `-' '._ _.' `-' '._ _.' `-' '._ _.' `-' '._ _.' `-' '._ (.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.) `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' -it's monkey business time! (version 1.5) */
why, that’s silly. you’d never do something so silly in your comments.
orly? does this look familiar?
+------------------------------------------------------------+ | module name: classmonkey | | module purpose: emulate a monkey | | inputs: bananas | | outputs: grunts | | throws: poop | +------------------------------------------------------------+
programmers love to go “touch up” their code to make it look good when their brain hurts and they want something easy to do for a while. it may be a waste of time, but at least they are wasting it during periods where they wouldn’t be productive anyway.
the trouble is that it creates a time-wasting maintenance tax imposed on anyone working with the code in the future just to keep the pretty little box intact when the text ruins the symmetry of it. even programmers who hate these header blocks tend to take the time to maintain them because they like consistency and every other method in the project has one.
how much is it bugging you that the right border on that block is misaligned? yeah. that’s the point.
(3) header blocks: nuisance or menace?
this one is going to be controversial, but i’m holding my ground. i don’t like blocks of header comments at the top of every file, method or class.
not in a boat, not with a goat.
why? well let me tell you, george mcfly…
they are enablers for badly named objects/methods – of course, header blocks aren’t the cause for badly named identifiers, but they are an easy excuse to not put in the work to come up with meaningful names, an often deceptively difficult task. it provides too much slack to just assume the consumer can just read the “inline documentation” to solve the mystery of what the dothemonkeything method is all about.
johnfx’s commandment:
the consumer of thy code should never have to see its source code to use it, not even the comments.
they never get updated: we all know that methods are supposed to remain short and sweet, but real life gets in the way and before you know it you have a 4k line class and the header block is scrolled off of the screen in the ide 83% of the time. out of sight, out of mind, never updated.
the bad news is that they are usually out of date. the good news is that people rarely read them so the opportunity for confusion is mitigated somewhat. either way, why waste your time on something that is more likely to hurt than help?
johnfx’s maxim of plagiarized ideas :
bad documentation is worse than no documentation.
exception: some languages ( java / c# ) have tools that can digest specially formatted header block comments into documentation or intellisense/autocomplete hints. still, remember rule (2) and stick to the minimum required by the tool and draw the line at creating any form of ascii art .
(4) comments are not source control
this issue is so common that i have to assume that programmers (a) don’t know how to use source control; or (b) don’t trust it.
archetype 1: “the historian”// method name: pitythefoo (included for the sake of redundancy) // created: feb 18, 2009 11:33pm // author: bob // revisions: sue (2/19/2009) - lengthened monkey's arms // bob (2/20/2009) - solved drooling issue void pitythefoo() { ... }
the programmers involved in the evolution of this method probably checked this code into a source control system designed to track the change history of every file, but decided to clutter up the code anyway. these same programmers more than likely always leave the check-in comments box empty on their commits.
i think i hate this type of comment worst of all, because it imposes a duty on other programmers to keep up the tradition of duplicating effort and wasting time maintaining this chaff. i almost always delete this mess from any code i touch without an ounce of guilt. i encourage you to do the same.
archetype 2: “the code hoarder”void monkeyshines() { if (monkeysonbed(jumping).count > max) { monkeysonbed.breakhead(); // code removed, smoothie shop closed. // leaving it in case a new one opens. // monkeysonbed.drink(bananasmoothie); } }
another feature of any tool that has any right to call itself a scm is the ability to recover old versions of code, including the parts you removed. if you want to be triple super extra sure, create a branch to help you with your trust issues .
(5) comments are a code smell
comments are little signposts in your code explaining it to future archaeologists that desperately need to understand how 21st century man sorted lists of purchase orders.
unfortunately, as donald norman explained so brilliantly in the design of everyday things , things generally need signs because their affordances have failed. in plain english, when you add a comment you are admitting that you have written code that doesn’t communicate its purpose well.
despite what your prof told you in college, a high comment to code ratio is not a good thing. i’m not saying to avoid them completely, but if you have a 1-1 or even a 5-1 ratio of loc to comments, you are probably overdoing it. the need for excessive comments is a good indicator that your code needs refactoring .
whenever you think, “this code needs a comment” follow that thought with, “how could i modify the code so its purpose is obvious?”
talk with your code, not your comments.
technique 1 : use meaningful identifiers and constants (even if they are single use)
// before // calculate monkey's arm length // using it's height and the magic monkey arm ratio double length = h * 1.845; //magic numbers are evil! // after - no comment required double armlength = height * monkey_arm_height_ratio;
technique 2: use strongly typed input and output parameters
// before // begin: flip the "hairy" bit on monkeys foreach(monkey m in thesemonkeys) { // 5-6 steps to flip bit. } // end: flip the "hairy" bit on monkeys // after no comment required fliphairybit(thesemonkeys);
as an added bonus, technique 3 will tend to reduce the size of your methods and minimizing the nesting depth ( see also “flattening arrow code” ) all of which contribute to eliminating the need for commenting the closing tags of blocks like this:
} // ... if see evil } // .. . while monkey do. } // ... if monkey see. } // ... class monkey } // ... namespace primate
acknowledgments
several of the ideas presented here, and a good deal of the fundamental things i know about programming as part of a team, and not as a lone-wolf working on a college project i learned from the book code complete by steve mcconnell. if you are a working programmer and have not read this book year, stop what you are doing and read it before you write another line of code.
from http://improvingsoftware.com/2011/06/27/5-best-practices-for-commenting-your-code/
Opinions expressed by DZone contributors are their own.
Comments