Name

STYL-06: Comment tersely with value-added information

Synopsis

The best way to explain what your code is doing is to let that code speak for itself. You can take advantage of many self-documentation techniques, including:

  • Use meaningful variable, procedure, and function names.

  • Use the language construct that best reflects the code you are writing (choose the right kind of loop for your logic, label loops and BEGIN-END blocks, etc.).

Whenever you find yourself adding a comment to your code, first consider whether it is possible to modify the code itself to express your comment. Good reasons to add comments include:

  • Program headers, explanations of workarounds, patches, operating-system dependencies, and other “exceptional” circumstances

  • Complex or opaque logic

Example

Let’s follow a trail of unnecessarily commented code to self-documenting code. We start with:

    -- If the first properties element is N...
    IF properties1 = 'N'

Yikes! Our line of code was incomprehensible and our comment simply repeated the code using the English language, rather than the stored program language. No added value, no real assistance, yet not at all uncommon. The least we can do is use the comment to “translate” from computer-talk to business requirement:

    -- If the customer is not eligible for a discount...
    IF properties1 = 'N'

That’s better, but we have created a redundancy: if our requirement ever changes, We have to change the comment and the code. Why not change the names of our variables and literals so ...

Get MySQL Stored Procedure Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.