Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CSE 331 Specifications slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia

Similar presentations


Presentation on theme: "1 CSE 331 Specifications slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia"— Presentation transcript:

1 1 CSE 331 Specifications slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

2 2 Discipline and modularity Two ways to view a program:  The implementer's view (how to build it)  The client's view (how to use it) It helps to apply these views to program parts:  While implementing one part, consider yourself a client of any other parts it depends on  Try not to look at those parts through an implementer's eyes This helps dampen interactions between parts Formalized through the idea of a specification.

3 3 Specifications specification: A set of requirements agreed to by the user and the manufacturer of a software unit or product.  Describes the client and implementer's expectations of each other. In object-oriented design, a class's spec describes all publicly visible behavior or attributes of that class.  the class's superclass and interfaces implemented (if any)  constructors  methods  public constants or fields (if any)  nested / inner types  any assumptions or guarantees made by the class

4 4 Benefits of specs Specs provide abstraction:  procedural abstraction (describe methods' behavior, not code)  data abstraction (describe classes' functionality, not implementation) Specs facilitate simplicity by two-way isolation:  Isolate client from implementation details  Isolate implementer from how the part is used  Discourages implicit, unwritten expectations Specs facilitate change:  The spec, rather than the code, gets "frozen" over time. How is a spec written down and documented?

5 5 Code as spec (bad) The class's author might say, "To understand how my class works, just look at its code." What's wrong with this? public boolean subList(List src, List part) { int part_index = 0; for (E element : src) { if (element.equals(part.get(part_index))) { part_index++; if (part_index == part.size()) { return true; } } else { part_index = 0; } } return false; }  Too much detail! Client only cares what it does, not how it does it.

6 6 Interface as spec (bad) The class's author might say, "To understand how my class works, just look at its public interface." Is this good or bad? public interface List { public int get(int index); public void set(int index, E value); public void add(E value); public void add(int index, E value);... public boolean subList(List src, List part); }  Not enough detail! Interface describes only the syntax, but the client also needs to understand in detail the semantics (behavior).

7 7 Comments as spec Comments are essential to properly specifying behavior.  But many comments are informal and incomplete: // checks to see if part appears within src public boolean subList(List src, List part) { In what ways are the above comments inadequate?  Must part 's elements appear consecutively, in the same order?  What if src is null? What if part is null?  What if either list is empty? What if both are empty?  What is the expected runtime of the method?  What value does it return if part is found, versus if it isn't? (arguably obvious, but not stated very clearly in the comments)

8 8 What is a better comment? If the previous comment is inadequate, is this one a better choice? // This method has a for loop that scans the "src" list from // beginning to end, building up a match for "part", and // resetting that match every time that a non-matching // element is found. At the end, it returns false if... public boolean subList(List src, List part) {  The above comments describe too many implementation details.  It is possible to describe behavior thoroughly without describing every detail of the code used to implement that behavior.

9 9 Spec by documentation The following comment header describes the behavior in detail: /** Returns whether all elements of part appear * consecutively within src in the same order. * (If so, returns true; otherwise, returns false.) * src and part cannot be null. * If src is an empty list, always returns false. * Otherwise, if part is an empty list, always returns true. *... */ public boolean subList(List src, List part) {  Note that it does not describe the code inside the method. Only describes what the method's externally visible behavior (return value) will be, based on its externally supplied parameters.

10 10 Spec exercise Suppose a method M takes an integer arg as an argument  Spec 1: "returns an integer equal to its argument"  Spec 2: "returns a non-negative integer equal to its argument"  Spec 3: "returns an integer ≥ its argument"  Spec 4: "returns an integer that is divisible by its argument"  Spec 5: "returns its argument plus 1" Which code meets which spec(s)?  Code 1: return arg;  Code 2: return arg + arg;  Code 3: return Math.abs(arg);  Code 4: return arg++;  Code 5: return arg * arg;  Code 6: return Integer.MAX_VALUE; ignore int overflow for all five. Spec1Spec2Spec3Spec4Spec5

11 11 Good documentation Good documentation comments describe the following:  the method's overall core behavior or purpose  preconditions (what the method requires)  postconditions (what the method promises) modifies:What objects may be affected by a call to this method?  (Any object not listed here is assumed to be untouched afterward.) throws:What errors or exceptions might occur? effects:Guarantees on the final state of any modified objects. returns:What values will the value return under what circumstances?

12 12 Spec exercise How would you specify the following method?  requires? (pre)  modifies? (post)  throws? (post)  effects? (post)  returns? (post) public static void uniquify(List lst) { for (int i = lst.size() - 1; i > 0; i--) { if (lst.get(i) == lst.get(i - 1)) { lst.remove(i); }

13 13 Benefits of specs Writing specs changes the incentive structure of coding:  rewards code that is easy to describe and understand  punishes code that is hard to describe and understand (even if it is shorter or easier to write) If you find yourself writing complicated specs, redesign:  subList code that does exactly the right thing may be slightly slower than a hack that assumes no partial matches before true matches; but cost of forcing client to understand the details is too high

14 14 Spec strength A weaker spec is one that requires more and/or promises less.  less work for the implementer of the code; more for the client  examples: doesn't work for negatives; requires sorted input; undefined results if the list contains duplicates; strings must be in valid format A stronger spec is one that requires less and/or promises more.  less work for the client, but harder to implement  examples: guaranteed to find a match; uses a default if a bad value is supplied; specifies behavior for entire range of input; runtime bounds If a spec S 2 is stronger than S 1, then for any implementation I,  I satisfies S 2  I satisfies S 1 Which kind of spec is better? (It depends.)

15 15 Strengthening a spec We can strengthen a specification by:  promising more make effects clause harder to satisfy put fewer objects in modifies clause  asking less of the client make requires clause easier to satisfy We can weaken a specification by:  promising less make effects clause easier to satisfy put extra objects in modifies clause  asking more of the client make requires clause harder to satisfy

16 16 Spec without code Specification means client doesn't need to see implementation.  So the code may not even exist yet! One strategy: Write specifications first, make sure system will fit together, and then assign each piece to a separate implementer.  Allows teamwork and parallel development  Also helps with testing Second strategy: Write specs first, write tests that verify the specs, then (lastly!) write the code to pass the tests.  test-driven development  Tools can help (e.g. spit out stub code for all classes based on tests).

17 17 Class as an ADT abstract data type (ADT): A description of a type in terms of the operations that can be performed on a given set of data.  abstracts from the details of data representation  a spec mechanism; a way of thinking about programs and designs Start your design by designing data structures  Write code to access and manipulate data

18 18 ADT implementation public class Point { private double x; private double r; private double y; private double theta; } Are the two above classes the same or different?  different:can't replace one with the other  same:both classes implement the concept "2-d point" Goal of ADT methodology is to express the sameness:  Clients depend only on the concept "2-d point". This is good: delays decisions fixes bugs allows performance optimizations

19 19 2-D point as ADT public class Point { // A 2-d point exists somewhere in the plane,... public double getX() public double getY() public double getR() public double getTheta() // can be created public Point() // new point at (0, 0) // can be modified public void translate(double dx, double dy) public void scaleAndRotate(double dr, double dtheta)... }

20 20 Abstraction barriers  The implementation is hidden.  The only operations on objects of the type are those that are provided by the abstraction. Point getX getY getR getTheta translate scaleAndRotate rest of program abstraction barrier clients implementation

21 21 Categories of methods accessor or observer: provide information about the callee  typically returns a value  never modifies the object's visible state (its "abstract value") creator: makes a new object (constructors, factory methods)  not part of pre-state: in effects clause, not modifies mutators: modifies state of the object on which it was called  each method has a side effect on the callee producers: creates another object(s) of the same type  common in immutable types, e.g. String substring  no side effects

22 22 Polynomial ADT /** A Polynomial represents a mutable polynomial with * integer coefficients. A typical Polynomial is * c 0 + c 1 x + c 2 x 2 +... */ public class Polynomial { // creators: produce new objects public Polynomial() public Polynomial(int c, int n) // observers/accessors: info about state of object public int degree() public int coefficient(int power) // mutators: change state of object public void add(Polynomial q) public void subtract(Polynomial q) public void multiply(Polynomial q) public void negate() }


Download ppt "1 CSE 331 Specifications slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia"

Similar presentations


Ads by Google