Code Comments
Basics
A comment is a line starting with //
.
Comments are just notes for the programmer, so they are not run as part of the program.
A comment can appear on a line by itself, or at the end of a code line.
// A standalone comment. // Here is another line. $a = 1 // Or next to a line of code.
To create a multi-line comment block, surrounding the text with /*
and */
.
/* This is a multi-line comment. */
How to Use Comments
Comments are useful for a few things:
1. Explaining code. Comments are used to explain parts of the program to any future reader — including yourself!
// Apply the Zuckerdorf Friendship Formula to determine // how close this friend is to the current user. $friendLevel = ($numFriendsInCommon * 1.2345) + 42
2. Disabling code. You can comment out lines of code temporarily while you’re working on the code around it. (Be careful not to clutter your files with too much unused code.)
$widgets = getWidgets() // showWidgets($widgets)
3. TODO's. You can record “To Do” reminders for the future.
// TODO: Add in the rest of the seven dwarves $dwarves = ['Sleepy', 'Sneezy', 'Doc']
Tips for Good Comments
Tip 1: Avoid comments that simply repeat what is in the code.
Example of a bad, redundant comment:
// Print the userName print($userName)
Tip 2: Good comments usually explain the “why” of the code. The code itself already tells you the “what”.
Example of a good comment that explains the “why”:
// The Shipping dept always adds an extra '#' sign // in their exported spreadsheet, so we need to remove it. $productId = $productId.replace('#', '')