SWE/CS 332 In Class Exercise # 5


Name(s):

public class Poly {

    private int[] trms;
    private int deg;

    // Effects: ???
    public Poly() {
       trms = new int[1]; trms[0] = 0;
       deg = 0;
    }

    // Effects: ???
    public Poly(int c, int n) {
       if (n < 0) {
          throw new IllegalArgumentException("Poly(int, int) constructor");
       }
       if (c == 0) {
          trms = new int[1]; trms[0] = 0;
          deg = 0;
          return;
       }
       trms = new int[n+1];
       for (int i=0; i < n; i++) {
          trms[i] = 0;
       }
       trms[n] = c;
       deg = n;
    }

    private Poly (int n) {
       trms = new int[n+1];
       deg = n;
    }

    // Effects: ???
    public int degree() {
       return deg;
    }

    // Effects: ???
    public int coeff(int d) {
       return (d < 0 || d > deg) ? 0 : trms[d];
    }

// Effects: ??? public Poly add(Poly q) { Poly la, sm; if (deg > q.deg) { la = this; sm = q; } else { la = q; sm = this; } int newdeg = la.deg; if (deg == q.deg) { for (int k = deg; k > 0; k--) { if (trms[k] + q.trms[k] != 0) { break; } else { newdeg--; } } } Poly r = new Poly(newdeg); int i; for (i = 0; i <= sm.deg && i <= newdeg; i++) { r.trms[i] = sm.trms[i] + la.trms[i]; } for (int j = i; j <= newdeg; j++) { r.trms[j] = la.trms[j]; } return r; } }

Liskov classifies methods into four kinds. What are they, and which ones are represented here? Which kinds are you most comfortable with?

Write some method contracts. What do you need to understand before you can even start? What do you need to be careful about? Develop several contracts for each given method, including some contracts that you think are plausible but inappropriate.

What is the role of the four types of methods when converting between mutable and immutable implementations?