4.2  Example: Compute the distance of a Posn to the origin

1. Data Analysis and Problem Analysis

No additional data needed, as the coordinates of the origin are known. We will compute the distance in city blocks, rather than finding the length of a direct line between the origin and the Posn that invokes the method.

2. Purpose and Contract/Header:

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

3. Examples:

Posn p1 = new Posn(10, 20);
Posn p2 = new Posn(20, 20);
// p1.distTo0()  -- expected: 30
// p2.distTo0()  -- expected: 40

4. Template:

The first varsion of the template is the same for all methods in a class.

  // ** DRAFT TEMPLATE ** Edit as needed.
  ??? mmm() {
    ... this.x ...
    ... this.y ...
  }

5. Program:

  // compute the distance of this Posn to the origin
  int distTo0() {
    return this.x + this.y;
  }

6. Tests:

We use the Test Tool, or write the tests in the Interactions Box:

/* Interactions:
p1.distTo0() == 30
p2.distTo0() == 40
*/

4.3  Example: Determine whether one Posn is closer to the origin than another one

1. Data Analysis and Problem Analysis

The method is invoked by one Posn. We need another Posn as an argument for this method. No additional information is needed.

2. Purpose and Contract/Header:

  // determine whether this Posn is closer to the origin
  // than the given Posn
  boolean closer(Posn that){...}

3. Examples:

  p1.closer(p2)  -- expected: true
  p2.closer(p1)  -- expected: false

4. Template:

  boolean closer(Posn that) {
    ... this.x ...         ... that.x ...
    ... this.y ...         ... that.y ...
    ... this.distTo0() ... ... that.distTo0() ...
  }

5. Program:

  // compute the distance from this Posn to the given Posn
  boolean closer(Posn that){
    return this.distTo0() < that.distTo0();
  }

6. Tests:

  p1.closer(p2) == true
  p2.closer(p1) == false