4.6  Example: Compute the distance of a rectangle to the origin

1. Data Analysis and Problem Analysis

The rectangle which invokes the method has all the information needed to solve the problem.

2. Purpose and Contract/Header:

  // compute the distance of this Rect to the origin
  int distTo0() { ... }

3. Examples:

  Rect r1 = new Rect(new Posn(10, 20), 40, 30);
  Rect r2 = new Rect(new Posn(20, 20), 10, 50);
  ...
  r1.distTo0()  -- expected: 30
  r2.distTo0()  -- expected: 40

4. Template:

We notice that a method distTo0() is already defined in the class Posn already. We add the method invocation of distTo0() by Posn nw to the template.

  // compute the distance of this Rect to the origin
  int distTo0() {
    ... this.nw ...
        ... this.nw.x ...
        ... this.nw.y ...
        ... this.nw.distTo0() ...
    ... this.width ...
    ... this.height ...
  }

5. Program:

 // compute the distance of this Rect to the origin
  int distTo0() {
    return this.nw.distTo0();
  }  

6. Tests:

  r1.distTo0()  == 30
  r2.distTo0()  == 40