Examples (aka Test Cases)

Pretend for a moment that the method is already defined. Write down two or more expressions that use this method (in correct Java syntax, so that if it were already defined, you could type them in and get answers), along with the "right answer" you expect each example to produce. This step is useful in at least three ways.

  1. It allows you to try out the syntax people will use to invoke the method, and perhaps learn that your first guess at the syntax is inconvenient to use, so you should change the syntax before wasting a lot of time implementing it.
  2. It allows you to discover, early on, that your contract wasn't quite right, and that you actually want different kinds of information going in or out. If that happens, change the contract now and re-write your examples accordingly; that will waste less time than going on and having to change the contract later.
  3. It gives you a ready source of test cases, already in legal Java syntax, thus removing one possible excuse for skipping the Testing step, later.

Start with the simplest possible examples, then work up to more and more complicated examples. For now, we'll write these as comments:

/**
 * cube : find the third power of a number.
 *
 * @param    num   the int to be cubed
 * @return   the number num^3, which is also an int
 */

/*
 MyClass.cube(0) should be 0
 MyClass.cube(5) should be 125
 MyClass.cube(-4) should be -64
 MyClass.cube(MyClass.cube(3)) should be 19683
*/
/**
 * howOld : produce a formatted message showing a person's name and how
 * old (s)he is.
 *
 * @param    name   a String indicating the person's name
 * @param    age    an int indicating the person's age in years
 * @return   a String, something like "Joe Schmoe is 21 years old."
 */

/*
 MyClass.howOld("Steve", 45) should be "Steve is 45 years old."
 MyClass.howOld("Bob", 22) should be "Bob is 22 years old."
*/

Note that every Java method "lives in" a class, and you need to specify the class when you call the method. The above examples assume that the methods live in a class named MyClass.

The problem with writing examples in a comment is that you still have to type them into the CodePad and check whether the answers match what you said they should be. In a few days, we'll see a more convenient way to write test cases.


Last modified: Tue Jan 14 13:32:32 EST 2003
Stephen Bloch / sbloch@adelphi.edu