5.3 Documentation with Comments
There are two parts to writing a program: One part is getting it to work (the functionality). The other part is the style: How did you write the program? Did you break it down into parts? Is it clear to read? This is where comments come into play!
Comments are a way for you to leave notes about what your code is doing in plain English so that other people can understand it.
Why comment?
Even though code is run by computers, it is read by other people. Comments help others understand your code. If you read your code ten years from now, would you be able to understand what it does?
The computer that runs your program knows to ignore comments if they are written as multi-line, single line, or Javadoc comments.
Use multi-line comments to leave a comment so a reader understands what your program or method is doing. The start of a multi-line comment uses /*
, each line following with a single *
, and ending the multi-line comment with */
.
Use single line comments to leave a comment for a single line in your code. For each single line comment, put two backslashes (//
) before the comment.
Another important part of commenting is using preconditions and postconditions. You can leave notes at the top of our methods about assumptions that you make.
Preconditions: A precondition is a condition that must be true just prior to the execution of a section of program code in order for the method to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
Postconditions: A postcondition is a condition that must always be true after the execution of a section of program code. Postconditions describe the outcome of the execution in terms of what is being returned or the state of an object.
This helps you think about the problem and make sure our methods line up.
Below is an example of the Power
class with comments.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
Which of the following is NOT a valid comment?
Add at least 7 comments the ActivityTracker
to your code to document the different steps that are happening. You can use either single-line or multi-line comments, but you should include enough information so that a person not familiar with the code can understand what the ActivityTracker
class is doing.
Then add JavaDoc style comments to each method in the ActivityLog
. Remember, you should start with a short description of the method, then use @param
or @return
to document any parameters or return values for the program.