Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Identifiers as Comments

The most important category of comments is method, variable, and class identifiers. Although not nearly as free-text as general comments, names are a trigger to the maintainer explaining what something is about, using your native language, in one to five words. The enforced brevity of these names is a boon to the maintenance programmer; they encourage the developer to compose units of code that are clearly focused.

Like comments, the compiler doesn't care about what these identifiers say. The computer cares only that all references to the same method, function, variable, or class are spelled the same. You can rename them to anything you want, even if the name is gibberish, and the compiler doesn't care as long as you're consistent and don't bump up against any old names. (The language geeks call this alpha renaming.)

Here's an example from the Ant Project class:

 * @param target is the Target to be added/replaced in
 * the current Project.
 * @param targetName is the name to use for the Target
public void addOrReplaceTarget(String targetName, Target target) {
     // code omitted

This is a pretty good name: The target will be added to the project. If it's already there, it will be replaced (rather than ignored, or added again). The programmer should have included at least one sentence for the Javadoc engine to grab, but the text would be redundant with the name of the method.

The word or is usually a bad thing in an identifier. It means that this one unit of code does more than one thing. When code does more than one thing, it's harder to keep all of the different users of that piece of code happy.

Method names are perhaps the ultimate redundancy; they say in a few words what the method is supposed to do. If the code of the method changes the meaning of the name, the name should be changed, just like a comment. When the name of the method is well chosen, as in this case, it often makes other forms of comments completely unnecessary.

The Javadoc methods here are not particularly helpful, but they don't need to be because the variable names were well chosen. It should be obvious that targetName designates "the name to use for the Target." It's helpful to have it there to make the Javadoc complete; incomplete Javadoc always has an unfinished feel to it, even if it's easy to guess what was meant.

  • + Share This
  • 🔖 Save To Your Account