New Perspectives On Web Design

(C. Jardin) #1
By Nicholas Zakas CHAPTER 2

that you make so many little decisions while writing code that it’s impossi-
ble to keep track of them all.
Writing code to a style guide transfers that information into the code
itself. When you decide when and where to use comments, as well as
which patterns should and shouldn’t be used, you leave a breadcrumb trail
for your future self to find your way back to the purpose of the code. It’s
incredibly refreshing to open up an old piece of code and have it look like
a new piece of code. You’re able to acclimate quickly, sidestepping the te-
dious process of relearning what the code does before you can start investi-
gating the real issue.
Any good style guide prescribes when and how to leave comments in
code. Most developers have an aversion to comments because it seems a lot
like writing documentation — and developers tend to hate writing docu-
mentation. This is usually because writing documentation is seen as time
not writing code. However, it’s the documentation that allows you to come
back to code you wrote in the past and quickly get back up to speed.
Another common argument against using comments is that code
should be self-documenting. In reality, there is no such thing as self-doc-
umenting code. Self-documenting code is a myth perpetuated by people
who hate to write documentation. A common argument against writing
comments is, “if you can’t understand my code, then you’re not smart
enough.” In reality, understanding code has nothing to do with how smart
a developer is, but rather providing enough context so the code make
sense. Without comments, or a direct discussion with the code author, it’s
very hard to get enough context.
The best-understood code is littered with comments explaining key
sections. You certainly don’t want a comment for every line of code, and
comments must provide additional context and information that cannot
otherwise be gleaned from reading the code. Here’s an example of a bad
comment:


// set initial count to 0
var count = 0;

Free download pdf