10 - Commenting
31.6 Laying Out Comments
Comments done well can greatly enhance a program's readability; comments done poorly can actually hurt it. The layout of comments plays a large role in whether they help or hinder readability.
Indent a comment with its corresponding code
Visual indentation is a valuable aid to understanding a program's logical structure, and good comments don't interfere with the visual indentation. For example, what is the logical structure of the routine shown in Listing 31-58?
Listing 31-58 Visual Basic example of poorly indented comments
For transactionId = 1 To totalTransactions
' get transaction data
GetTransactionType( transactionType )
GetTransactionAmount( transactionAmount )
' process transaction based on transaction type
If transactionType = Transaction_Sale Then
AcceptCustomerSale( transactionAmount )
Else
If transactionType = Transaction_CustomerReturn Then
' either process return automatically or get manager approval, if required
If transactionAmount >= MANAGER_APPROVAL_LEVEL Then
' try to get manager approval and then accept or reject the return
' based on whether approval is granted
GetMgrApproval( isTransactionApproved )
If ( isTransactionApproved ) Then
AcceptCustomerReturn( transactionAmount )
Else
RejectCustomerReturn( transactionAmount )
End If
Else
' manager approval not required, so accept return
AcceptCustomerReturn( transactionAmount )
End If
End If
End If
Next
In this example, you don't get much of a clue to the logical structure because the comments completely obscure the visual indentation of the code. You might find it hard to believe that anyone ever makes a conscious decision to use such an indentation style, but I've seen it in professional programs and know of at least one textbook that recommends it.
The code shown in Listing 31-59 is exactly the same as that in Listing 31-58, except for the indentation of the comments.
Listing 31-59 Visual Basic example of nicely indented comments.
For transactionId = 1 To totalTransactions
' get transaction data
GetTransactionType( transactionType )
GetTransactionAmount( transactionAmount )
' process transaction based on transaction type
If transactionType = Transaction_Sale Then
AcceptCustomerSale( transactionAmount )
Else
If transactionType = Transaction_CustomerReturn Then
' either process return automatically or get manager approval, if required
If transactionAmount >= MANAGER_APPROVAL_LEVEL Then
' try to get manager approval and then accept or reject the return
' based on whether approval is granted
GetMgrApproval( isTransactionApproved )
If ( isTransactionApproved ) Then
AcceptCustomerReturn( transactionAmount )
Else
RejectCustomerReturn( transactionAmount )
End If
Else
' manager approval not required, so accept return
AcceptCustomerReturn( transactionAmount )
End If
End If
End If
Next
In Listing 31-59, the logical structure is more apparent. One study of the effectiveness of commenting found that the benefit of having comments was not conclusive, and the author speculated that it was because they "disrupt visual scanning of the program" (Shneiderman 1980). From these examples, it's obvious that the style of commenting strongly influences whether comments are disruptive.
Set off each comment with at least one blank line
If someone is trying to get an overview of your program, the most effective way to do it is to read the comments without reading the code. Setting comments off with blank lines helps a reader scan the code. An example is shown in Listing 31-60:
Listing 31-60 Java example of setting off a comment with a blank like.
// comment zero
CodeStatementZero;
CodeStatementOne;
// comment one
CodeStatementTwo;
CodeStatementThree;
Some people use a blank line both before and after the comment. Two blanks use more display space, but some people think the code looks better than with just one. An example is shown in Listing 31-61:
Listing 31-61 Java example of setting off a comment with two blank lines.
// comment zero
CodeStatementZero;
CodeStatementOne;
// comment one
CodeStatementTwo;
CodeStatementThree;
Unless your display space is at a premium, this is a purely aesthetic judgment and you can make it accordingly. In this, as in many other areas, the fact that a convention exists is more important than the convention's specific details.
Commenting code: Bad Idea? (video)
"You should not comment every line of code"
Why do we comment our code
- Especially for beginner programmers
- Clear up confusion for others
- Make it easier for ourselves
- for whenever we revisit our code
- Notes and reminders of how logic works
What's bad about this?
- Comments quickly become obsolete after code change
- The compiler doesn't check your comments to see if they still make sense
- It is hard to maintain comments as well
- Developers use comments as a crutch for following bad practices
- Comments sprinkled everywhere makes code visually harder to read sometimes
Bad comments
What is wrong with these comments?
/**
Show alert
- returns: the action that was selected
- parameters:
- x: The title you want to show
- y: The message for your alert
- z: The cancel action title
*/
func show(x: String, y: String) {
let alertControllér = UIAlertController(title: x, message: y,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .cancel,
handler: nil))
present(alertController, animated: true, completion: nil)
}
- The first issue is the
returns:line. The function is not returning anything so this line doe snot make sense - The function only contains parameters x and y, not z, so we should remove the "z" comment line as well.
- The name for the function should be more descriptive
func showAlertForditle(_ title: String, message: String) {
let alertController = UIAlertController(title: title, message:
message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .cancel,
handler: nil))
present(alertController, animated: true, completion: nil)
}
- The benefits is that the code is self documenting, how this function works is obvious just by looking the names
Self-documenting Code
- Let your code do the talking
Tips on coding style
- Use variable names that are self-explanatory
- Function names should read aloud like plain english
- Keep functions short (<10 lines)
- Refactor long methods to provide sensible structure
- Don't write spaghetti code
Rule of thumb
- Don't comment the obvious
- Don't comment what your code is doing
- Only comment why you're doing it
Good comments
- Bug fixes related to underlying framework
- Why you decided to go with a complicated implementation
- To-do comments
- Comment business logic that isn't obvious to new developers
- Etc.....
Comments vs Documentation
- A big difference between internal comments and public documentation
- Documentation makes integration easy
- Good documentation leads to wider adoption
Personal Preferences
- Less comments and more readable code
- Well-defined variables, functions, and inputs
- If you think your code will be confusing in the future, refactor it now