CHAPTER 2 Writing Maintainable, Future-Friendly Code
This comment provides no additional context or information to the
line of code it describes. Comments of this type should be avoided at all
costs. A good comment includes information such as:
- A description of what the code is doing,
- Why the code is doing it in this way (as opposed to an alternative),
- A reference to any related bug or issue in an issue tracker.
For example, here is an excellent comment from the jQuery codebase:
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
The comment references an issue number and provides a description
of the original bug. The second comment describes the approach that fixes
the issue. It’s very easy for anyone reading over the code to understand
why this code was included and where to go if more information is re-
quired. Here’s another good example from the YUI CSS library:
h1 {
/*18px via YUI Fonts CSS foundation*/
font-size:138.5%;
}