1.8 Documentation with Comments and Preconditions

From CS Awesome 2CC BY-NC-SA 4.0Original page

Java1 class period3 exercises4 graded tests

Files

README.mdDownload

1.8 Documentation with Comments and Preconditions

Each coding exercise has its own folder. Open its .java file and press Run to try it. Run Tests checks every graded exercise in this lesson at once.

Comments

Adding comments to your code helps to make it more readable and maintainable. In the commercial world, software development is usually a team effort where many programmers will use your code and maintain it for years. Commenting is essential in this kind of environment and a good habit to develop. Comments will also help you to remember what you were doing when you look back to your code a month or a year from now. Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run.

There are 3 types of comments in Java:

  1. // Single line comment
  2. /* Multiline block of comments */
  3. /** Java documentation comments */

The special characters // are used to mark the rest of the line as a comment in many programming languages. If the comment is going to be multiple lines, we use /* to start the comment and */ to end the comment.

There is also a special version of the multi-line comment, /** ... */, called the documentation comment. Java has a cool tool called javadoc that comes with the Java JDK that will pull out all of these comments to make documentation of a class as a web page. This tool generates the official Java documentation too, for example for the String class. Although you do not have to use this in the AP exam, it’s a good idea to use the documentation comment in front of classes, methods, and instance variables in case you want to use this tool later on to save your code as a library.

Check your understanding: Drag the definition from the left and drop it on the correct symbols on the right. — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-1-8-comments.html#comments

The compiler will skip over comments, and they don’t affect how your program runs. They are for you, your teacher, and other programmers working with you. Here are some examples of good commenting:

/**
* MyClass.java
* @author My Name
* @since Date
* This class keeps track of the max score.
*/
public class MyClass
{
   private int max = 10; // this keeps track of the max score
   /* The print() method prints out the max */
   public void print()
   {
      System.out.println(max);
   }
}

Note that most IDEs will tend to show comments formatted in italics – to make them easier to spot.

Notice that there are some special tags that you can use in Java documentation. These are not required but many programmers use them. Here are some common tags:

  • @author Author of the program
  • @since Date released
  • @version Version of program
  • @param Parameter of a method
  • @return Return value for a method
Exercise 1

The code will read in the 2 numbers in input.txt and multiply them. Add a multiline comment above the public class to describe what the class does and add single-line comments above each section of the code to read in, calculate, and print the result to describe what it does.

Open the 01-commentExercise folder and edit Multiply.java. Press Run to try it; Run Tests checks it (2 tests). Run feeds it the input in input.txt; change that file to try other input. Its tests check your code, not what it prints: “Contains /*”, “Contains //”.

Preconditions and Postconditions

Many methods in API libraries have preconditions and the postconditions described in their comments. A precondition is a condition that must be true for your method code to work, for example the assumption that the parameters, the data that you give the method to do its job, have values within limits and are not null. The methods could check for these preconditions, but they do not have to. The precondition is what the method expects in order to do its job properly.

A postcondition is a condition that is true after running the method. It is what the method promises to do. Postconditions describe the outcome of running the method, for example what is being returned from the method or the changes to the state. These assumptions are very useful to other programmers who want to use that method and get the correct results.

One precondition that we talked about is that divisors cannot be zero in expressions because that will cause the code to have a runtime error or exception. Many math functions have preconditions about their operands because not every mathematical operation is defined for every value. For example, computing the square root of a negative number is undefined, so the Math.sqrt(num) Java method, which we will learn later, will return a special value NaN which stands for “not a number” if num is negative. But since you can’t really do anything useful with NaN it’s better to think of sqrt as having a precondition that says it only works properly if given a positive argument. These are described as special cases in the API documentation, for example in https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/lang/Math.html#sqrt(double). Try this out below.

Exercise 2

The code uses the square root method in Java which has a precondition that the number that you give it is not negative. When you press Run, the compiler will not catch the error, but it will return the error value NaN. Can you fix the value of num so that it does not return NaN? What is the precondition for the Math.sqrt method?

Open the 02-math-preconditions folder and edit SqRoot.java. Press Run to try it; Run Tests checks it (1 test). Its test checks your code, not what it prints: “Code does not contain -4”.

Here is an example of preconditions, postconditions, and @param in the Turtle code that we use for animating turtle drawings. The Turtle forward method’s precondition is that the amount of pixels forward should be between 0 and the width and height of the world. If it receives value out of this range, it sets pixels to the closest legal values that it can so that the turtle appears just at the edge of the world.

/**
 * Method to move the turtle forward the given number of pixels
 * @param pixels the number of pixels to walk forward in the heading direction
 * Preconditions: parameters pixel is between 0 and
 *    the width and height of the world.
 * Postconditions: the turtle is moved forward by pixels amount
 *   but stays within the width and height of the world.
 */
public void forward(int pixels)
{
  /* code to move the turtle forward */
}
Exercise 3

Try to break the preconditions of the Turtle forward method below. Can you make it go completely off screen by changing the number of pixels given to the forward method in line 13? What happens if you put in negative numbers?

Open the 03-turtle-preconditions folder and edit TurtlePreconditions.java. Press Run to try it; Run Tests checks it (1 test). Its test checks your code, not what it prints: “Change forward(100) to try to break preconditions”. It draws pictures: Run saves the drawing as an image in its folder, and Run Tests checks the code without the drawing.

Software Validity and Use-Case Diagrams

Preconditions and postconditions are covered on the AP CSA exam. Software validity, testing, and use-case diagrams which are discussed in this subsection are not covered on the AP CSA exam, but they are described here because they use preconditions and postconditions and are used by professional programmers.

Determining the preconditions and postconditions help us to test our code and determine the validity of our software. Software validity tests whether the software does what it is supposed to do before it is released. This is sometimes very important. For example, if the code is part of a satellite going to outerspace or is going to be used in an emergency condition, we want to test it thoroughly and make sure it works and is valid before it is put into use.

Good software testers actually try to break the code! They try all kinds of input to see what the software will do because you never know what users will try or what conditions there will be. So, always think what the preconditions of your code are and see what happens when you break them, and then see if you can protect or warn against that.

Preconditions and postconditions can also help us to design better software systems. Software designers often first draw a high-level Use-Case Diagram of a system that shows the different ways that a user might interact with a system before they build it. Here is a simple Use-Case Diagram of a restaurant system. It shows 2 actors in the system: the customer and the staff at the restaurant, and 3 use-cases in circles. A Use-case is a particular user interaction or situation in the system or software, and they often become methods in the program.

Use-Case Diagram of a Restaurant System

Use-Case Diagram of a Restaurant System

After drawing a Use-Case Diagram, designers write down the preconditions and the postconditions for each Use-Case. Often the successful post-condition for one use-case becomes the preconditions for the next use-case. For example, for the “Order Food” and “Eat Food” Use Cases:

  • Preconditions for “Order Food”: Customer enters restaurant. Staff is ready to take the order.
  • Postconditions for “Order Food”: Customer orders the food. Staff takes the order.
  • Preconditions for “Eat Food”: Customer has already ordered food. Staff has delivered food.
  • Postcondition for “Eat Food”: Customer eats the food.

What are the preconditions and postconditions of the use-case “Pay for food”? Remember that these are often related to the other use-case conditions “order food” and “eat food”.

Discuss this with your class, or answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-1-8-comments.html#payconditions

Agile Software Development

There are many different models for software development. The waterfall model, developed in the 1970s, is a step by step model where each phase is finished before the next phase begins. This model has recently been criticized because it is not very adaptable. The more recent Agile development model involves iterative, incremental development where teams works in short 2-3 week sprints to completely develop, test, and release a component of the project to the customer for feedback. It is very adaptable as project requirements change because of early testing, immediate customer feedback and collaboration.

Waterfall vs Agile Models

Waterfall vs Agile Models

One very popular type of agile development is called Scrum. The following short video describes software development with Scrum.

Group Exercise

Try the Wake Up In the Morning Game in groups to practice the iterative and incremental agile development process.

Coding Challenge: Preconditions in Algorithms

Working in pairs or groups, come up with 4 steps that a user must do to purchase a product, for example a book on Java, in an online store, and list the preconditions and postconditions for each step. You could pretend to buy something online to come up with the steps. (You could use an online drawing tool like Creately.com (choose Use-Case Diagrams) to draw a Use-Case diagram for the Online Store System, but it is not required). Don’t forget to list the preconditions and postconditions for each step. You can type in your answer below.

Write down 4 steps that a user must do to purchase a product, for example a book on Java, in an online store, and list the preconditions and postconditions for each step.

Discuss this with your class, or answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-1-8-comments.html#challenge-1-8-use-case-preconditions

Summary

  • (AP 1.8.A.1) Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run.
  • (AP 1.8.A.1) Three types of comments in Java include /* */, which generates a block of comments, //, which generates a comment on one line, and /** */, which are Javadoc comments and are used to create API documentation.
  • (AP 1.8.A.2) 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.
  • (AP 1.8.A.3) 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 current value of the attributes of an object.

AP Practice

Check your understanding: Consider the following method.

/** method to add extra-credit to the score **/
       public double computeScore(double score, double extraCredit)
       {
           double totalScore = score + extraCredit;
           return totalScore;
       }

Which of the following preconditions are reasonable for the computeScore method?

Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-1-8-comments.html#AP-preconditions

For teachers

1.8 Documentation with Comments and Preconditions

Students read CSAwesome2's “Documentation with Comments and Preconditions” in CS Room and work through its 3 Java coding exercises.

  • Time: 1 class period
  • Tests: 4 in 3 graded exercises, set up for you when you import the lesson

Goals

  • (AP 1.8.A.1) Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run.
  • (AP 1.8.A.1) Three types of comments in Java include /* */, which generates a block of comments, //, which generates a comment on one line, and /** */, which are Javadoc comments and are used to create API documentation.
  • (AP 1.8.A.2) 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.
  • (AP 1.8.A.3) 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 current value of the attributes of an object.

Before class

In class

  1. Students read README.md. Questions that need CS Awesome's interactive widgets link back to it.
  2. Students do exercises 01–03, each in its own folder, pressing Run to try their code.
  3. Run Tests checks every graded exercise at once; scores appear in the Gradebook. Grading uses your copy of the tests, so a student who edits theirs does not change the grade.

Exercises

FolderFileGradingTests
01-commentExerciseMultiply.javaChecks code text only2
02-math-preconditionsSqRoot.javaChecks code text only1
03-turtle-preconditionsTurtlePreconditions.javaChecks code text only (draws pictures; graded without the drawing)1

Teachers can download a reference solution after signing in.