The Design Recipe for Methods (version 1)

Steps in writing a method

  1. Write the method contract and purpose (either in plain English or in javadoc form). This answers several questions: what's the name of the method, how many parameters does it expect in what order, what types are they, what type of answer does it produce, and what is the method supposed to do? These might look something like

    // myMethod takes in an int and returns a WorldImage
    // Result should be a blue circle of the specified size.
    
    or in javadoc,
    /**
     * myMethod: Produce a blue circle of the specified size.
     *
     * @param size   an int indicating the radius of the circle
     * @return       a WorldImage
     * @author       Stephen Bloch
     * @version      Feb. 1, 2013
     */
    

  2. Write test cases in a separate test class: if your class was named Homework1, the test class might be named Homework1Test.

    For methods that return a WorldImage, people often come come up with a “right answer” that is wrong in exactly the same way as the method is wrong, so it'll pass the test case without actually being correct. As a result, you'll think it's correct, you'll turn it in, I'll notice that it's wrong, and you'll lose points. To prevent this, it's a good idea to show(); them as well:

    public void testMyMethod (Tester t)
    {
        t.checkExpect (Homework1.myMethod (3), AImage.makeCircle(3,Color.blue,Mode.OUTLINED));
        Homework1.myMethod (3).show();
    }
    
    This way you can look at the result and decide for yourself whether it's what you expected; if not, you can fix the method (and the wrong “right answer”) before turning it in.

  3. Write the method skeleton:

    static WorldImage myMethod (int size)
    {
    }
    

  4. Add an inventory (in comments) between the curly-braces of the method skeleton:

    static WorldImage myMethod (int size)
    {
        // size     an int
    }
    
  5. Fill in the method body after the commented inventory:
    static WorldImage myMethod (int size)
    {
        // size     an int
        return AImage.makeCircle (size, Color.blue, Mode.OUTLINED);
    }
    
  6. Test your method: if you wrote your examples using Tester, you can either hit the "Run Test Cases" button, or right-click on the test class and choose "testEverything()", then look at the Terminal window to see how many tests it failed. And for methods that return an image, make sure to look at the shown results and decide whether they look right.