SWE 619 Quiz Number 3
September 21, 2011


  1. The code below uses Liskov's immutable Poly abstraction from Chapter 5. Recall that a typical Poly is c0 + c1 x + c2 x^2 + ...
    What is the value of p, expressed as a typical Poly, after lines 1 through 3? Note that the constructor is Poly (coefficient, exponent).
            Poly p =   new Poly(2, 3);   // line 1
            p = p.add (new Poly(5, 0));  // line 2
            p = p.add (new Poly(4, 3));  // line 3
    	
    Answer:
            after line 1:  p = 2 x^3
            after line 2:  p = 5 + 2 x^3
            after line 3:  p = 5 + 6 x^3
    	
    Note on grading: I'll accept explicit mention of 0 coefficients, and I'll accept different orderings of terms. I'll also accept answers that only give the final value after line 3.
  2. Suppose that the toString() method in Poly was written:
       public String toString () {
          String result = "Variable trms = [";
          for (int i=0; i < trms.length; i++ ) {
             result += trms [i] + " ";
          }
          result += "]; Variable deg = " + deg;
          return result;
       }
    
    What is wrong with such an implementation?
    Answer: The problem is that toString is based on the particular representation of trms and deg. toString() should be written to return the abstract state. To see why this would be a problem, suppose the implementation of Poly were changed to be a linked list of (coefficient, exponent) pairs for nonzero coefficients.
  3. The Poly method coeff() has the specification:
    public int coeff (int d)  
       // Effects: returns the coefficient of the term of this whose exponent is d
    
    Rewrite the specification to use exception handling to deal with case of negative exponents. Follow Bloch in choosing an appropriate standard Java exception.
    Answer:
       // Effects: if d < 0 throw IllegalArgumentException else
       //      returns the coefficient of the term of this whose exponent is d