abstraction, specification and verification. comp 302, spring 2005 2 abstraction hiding or...

34
Abstraction, Specification and Verification

Upload: damon-craig

Post on 18-Jan-2018

229 views

Category:

Documents


0 download

DESCRIPTION

Comp 302, Spring Two Program Fragments // search upwards found = false; for (int i = 0; i < a.length; i++) if (a[i] == e) { z = i; found = true; } // search downwards found = false; for (int i = a.length-1; i >= 0; i--) if (a[i] == e) { z = i; found = true; }

TRANSCRIPT

Page 1: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Abstraction, Specification and Verification

Page 2: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 20052

Abstraction Hiding or overlooking detail that is not relevant for the

task at hand Abstraction in software programs

Machine language (assembly) C-like languages High-level languages

Page 3: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 20053

Two Program Fragments// search upwardsfound = false;for (int i = 0; i < a.length; i++)

if (a[i] == e) {z = i;found = true;

}

// search downwardsfound = false;for (int i = a.length-1; i >= 0; i--)

if (a[i] == e) {z = i;found = true;

}

Page 4: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 20054

In a higher-level languagefound = false;if (found)z = a.indexOf(e);

Page 5: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 20055

Abstraction by Specification A specification allows us to separate the body of a

procedure (its implementation) from the computation it is intended to perform.

int addSquares1(int m, n){

return m*m + n*n; }

int addSquares2(int m, n){if (m == 0) {return n*n;

} else if (n == 0) {return m*m;

} else {return m*m + n*n;

} }

Page 6: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 20056

Specification

int addSquares1(int m, n) {// @effects: returns the sum of the squares of m and n

return m*m + n*n; }

int addSquares2(int m, n) { // @effects: returns the sum of the squares of m and n

if (m == 0) {return n*n;

} else if (n == 0) {return m*m;

} else {return m*m + n*n;

} }

Page 7: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 20057

Pre- and post- conditionsfloat sqrt(float coef) {// @requires: coef > 0// @effects: returns an approximation of the squareroot of coef

float ans = coef / 2.0;int i = i;while (i<7) {

ans = ans – ((ans * ans – coef)/(2.0 * ans));i = i+1;

}return ans;

} Pre-condition: coef > 0.

Must hold when the procedure is called Often used to ensure proper operation of procedure

Post-condition: Holds at the completion of procedure

Page 8: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 20058

Pre- and post-conditions Someone other than the developer of the procedure can

use it by understanding the pre- and post-conditions Also called “assume-guarantee” The procedure assumes that the pre-condition is true

when it is called, and guarantees that the post-condition holds when it returns.

Page 9: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 20059

Specification Abstractions must have precise definitions

Specifications We will use informal but precise specifications

Possible to have completely formal specification languages but more difficult to read

A specification language is not a programming language. Not executable, but shorter and easier to read.

Page 10: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200510

Specifications of Procedural Abstractions Specification of a procedure has two parts

Procedure header Semantic specification.

Procedure Header Lists arguments, their order and types The type of the result Exceptions thrown

Examples: void removeDupls (Vector v); float sqrt (float x);

Similar in form to the form of a function definition. f:integer integer

Page 11: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200511

Semantic Specs of Procedural Abstractions Semantic specification

The “@requires” clause (Precondition) The “@modifies” clause The “@effects” clause (Postcondition)

//REQUIRES: This clause states any constraints on use//MODIFIES: This clause identifies all modified inputs//EFFECTS: This clause defines the behavior

Procedure specification:

return_type pname (...)//REQUIRES: This clause states any constraints on use//MODIFIES: This clause identifies all modified inputs//EFFECTS: This clause defines the behavior

Page 12: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200512

Specifications of Classesvisibility cname {

//OVERVIEW: This clause defines the purpose of the class as a whole.

visibility static p1 ...visibility static p2 ...

}

Page 13: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200513

Examplepublic class Arrays {

// OVERIEW: This class provides a number of standalone procedures// that are useful for manipulating arrays of ints.

public static int search (int[] a, int x) // EFFECTS: If x is in a, returns an index where // x is stored otherwise, returns -1.

public static int searchSorted (int[] a, int x) // REQUIRES: a is sorted in ascending order // EFFECTS: If x is in a,returns an index where // x is sorted otherwise returns -1.

public static void sort (int [] a) // MODIFIES: a // EFFECTS: Rearranges the elements of a into

// ascending order // e.g., if a=[3,1,6,1] before // the call, on return a = [1,1,3,6].

}

Page 14: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200514

Total vs. Partial Procedures Total procedure: No “@requires” clause

Works on all inputs. No restriction. Partial procedures have an “@requires” clause

If inputs don’t satisfy this clause, then no guarantees Partial procedures are less safe

Avoid when possible Check “@requires” clause when not expensive

Sometimes partial procedures are more efficient searchSorted

Page 15: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200515

The _post notation

public static void sort (int [] a)

// MODIFIES: a // EFFECTS: Rearranges the elements of a into

// ascending order // For example, if a=[3,1,6,1], a_post = [1,1,3,6].

Page 16: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200516

The @modifies clausepublic static int[] boundArray (int[] a, int n)

// EFFECTS: Returns a new array containing the // elements of a in the order they appear in a // except that any elements of a that are greater

// than n are replaced by n.

No @modifies clause Can NOT return the input itself even if no element exceeds n

Spec says it must return new array

Page 17: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200517

public static void copyLine()// REQUIRES: System.in contains a line of text// MODIFIES: System.in and System.out// EFFECTS: Reads a line of text from System.in,

// advances the cursor in System.in to the end of // the line, and writes the line on System.out.

Implicit inputs System.in

public static final InputStream in The "standard" input stream. This stream is already open and ready to supply input

data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user

System.out public static final PrintStream out

The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user. For simple stand-alone Java applications, a typical way to write a line of output data is:

System.out.println(data)

Page 18: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200518

3.4 Implementing Procedures: Examplepublic class Arrays {

// OVERVIEW:This class provides a number of standalone procedures // that are useful for manipulating arrays of ints.

public static int searchSorted (int [] a, int x) { // REQUIRES: a is sorted in ascending order. // EFFECTS: If x is in a, returns an index where

// x is stored; otherwise, returns -1. // uses linear search

if (a == null) return -1;for (int i = 0; i < a.length; i++)

if (a[i] == x) return i; else if (a[i] > x) return -1;

return -1;}

//other static methods go here}

Page 19: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200519

public class Arrays {//OVERVIEW: ...

public static void sort (int[] a) {

//MODIFIES:a //EFFECTS:Sorts a[0], ..., a[a.length-1] into ascending order.

if (a == null) return; quickSort(a, 0, a.length-1); }

private static void quickSort(int[] a, int low, int high) {

//REQUIRES:a is not null and 0<=low&high<a.length //MODIFIES:a //EFFECTS:Sorts a[low],a[low+1],...,a[high] into ascending order.

if (low >= high) return; int mid = partition(a, low, high); quickSort(a, low, high); quickSort(a, mid + 1, high); }

Page 20: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200520

public class Arrays {// continued

private static int partition(int[]a, int i, int j) {

// REQUIRES:a is not null and 0 <= i < j < a.length // MODIFIES:Reorders the elemnts in a into two contiguous groups

// a[i],...,a[res] and // a[res+1],...,a[j], such that each element in the second group is

// at least as each // element of the first group. Returns res.

int x = a[i];while (true) {

while (a[j] > x) j--;while (a[i] < x) i++;if (i <j) { //need to swap

int temp = a[i]; a[i] = a[j]; a[j] = tempj--;i++; }

else return j; }

} }

Page 21: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200521

3.4 Implementing Procedurespublic class Vectors {

// OVERVIEW: Provides useful standalone procedures // for manipulating vectors.

public static void removeDupls (Vector v) { // REQUIRES:All elements of v are not null. // MODIFIES:v // EFFECTS:Removes all duplicate elements from v; // uses equals to determine duplicates. // The order of remaining elements may change.

if (v == null) return;for (int i = 0; i < v.size(); i++) {

Object x = i + 1;int j = i + 1;//remove all dupls of x from the rest of vwhile (j < v.size())

if (!x.equals(v.get(j))) j++;else { v.set(j, v.lastElement());

v.remove(v.size()-1); }}

}}

Page 22: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Verifying Data Abstractions

Page 23: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200523

Data Abstraction

data abstraction = <objects,operations>

Why data abstractions?

When the implementation of the abstraction changes, programs that use it don’t have to change.

Only access the object through methods it provides Can avoid making implementation decisions too early

Avoid inefficiencies and massive re-implementation Can first define the abstract type with its operations

Can then work on using modules Make implementation decisions later

Page 24: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200524

Outline How to specify data abstractions? How to implement data abstractions?

Page 25: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200525

Specifications for Data Abstractionsvisibility class dname {

// OVERVİEW: A brief description of the // behaviour of the type’s objects goes here

//constructors//specs for constructors go here

//methods//specs for methods go here

}

Page 26: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200526

Specification of IntSet (code filled in later)public class IntSet {

//OVERVİEW: IntSets are mutable, unbounded sets of integers//A typical IntSet is {x1,...,xn}.

//constructorspublic IntSet ( )

//EFFECTS: Initialize this to be empty. (no need for MODIFIES clause)

//methodspublic void insert (int x)

// MODIFIES: this// EFFECTS: Adds x to the element of this, // i.e., this_post = this + {x}

public void remove (int x)// MODIFIES: this// EFFECTS: Removes x from this, i.e., this_post = this – {x}

public boolean isIn (int x)// EFFECTS: If x is in this returns true else returns false

public int size ()// EFFECTS: Returns the cordinality of this

public int choose () throws EmptyException// EFFECTS: If this is empty, throws EmptyException

// else returns an arbitrary element of this.}

mutators

observers

Page 27: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200527

Mutability States of immutable objects never change

They are created and they stay that way until destroyed Example: Strings Huh? What about

String myFirstName = “Serdar”;String myLastName = “Tasiran”;String myFullName = myFirstName + “ “ + myLastName;

A new String object is created. The String with “Serdar” in it is never changed.

Mutable objects: Example: Arrays. a[i] = 5; If a mutable object is shared, a modification of one modifies the other.

Page 28: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200528

public class Poly {//OVERVIEW: Polys are immutable polynomials with integer coefficients.//A typical Poly is c0 + c1x + c2x2 + ... + cnxn

//constructorspublic Poly ()

//EFFECTS: Initializes this to be zero polynomial

public Poly (int c, int n) throws NegativeExponentException// EFFECTS: If n<0 throws NegativeExponentException else initalizes this

// to be the Poly cxn.

//methodspublic int degree ()

// EFFECTS: Returns the degree of this, i.e., the largest exponent with a // non-zero coefficient. Returns 0 if this is zero Poly.

public int coeff (int d)// EFFECTS: Returns the coefficient of the term of this whose exponent is

// d.

public Poly add (Poly q) throws NullPointerException// EFFECTS: If q is null throws NullPointerException else returns the Poly // this

+q.

public Poly mul (Poly q) throws NullPointerException// EFFECTS: If q is null throws NullPointerException else returns the Poly // *q.

public Poly sub (Poly q) Throws NullPointerException// EFFECTS: If q is null throws NullPointerException else returns the Poly // this –

q.

public Poly minus ()//EFFECTS: Returns the Poly – this.

}

Page 29: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200529

Using Data Abstractionspublic static Poly diff (Poly p) throws NullPointerExcepyion {

//EFFECTS: If p is null throws NullPointerException //else returns the Poly obtained by differentiating p.

Poly q = new Poly ();for (int i = 1; i <= p.degree(); i++)

q = q.add(new Poly(p.coeff(i)*i, i - 1));return q;

}

public static IntSet getElements (int[] a)throws NullPointerException {

//EFFECTS: If a is null throws NullPointerException //else returns a set containing an entry for each //distinct element of a.

IntSet s = new IntSet();for (int i = 0; ,< a.length; i++) s.insert(a[i]);return s;

}

Page 30: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200530

Implementing Data Abstractions

Must select a representation (rep). Examples:

A Vector (from java.util) of Integer objects is a possible rep for IntSet A Vector containing Gizmo objects may be the rep for Board in your

project. Reps must

Support all operations in a simple way Provide efficient implementations

Searching an entry should not require looking at all entries, ideally.

Page 31: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200531

A Rep for IntSet Should we allow each element to occur more than once

or not If we do, insertion is simple: Just add it at the end of the Vector But remove and isIn take a long time

isIn is likely to be called a lot Forbid duplicates in Vector

Page 32: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200532

Implementing Data Abstractions A representation typically has several components

Correspond to (non-static) fields in the class definitions These are also called instance variables

There is a separate set of them for each object Instance variables must not be visible to users, other classes

Make them private Provide methods to access and modify them

Page 33: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200533

public class IntSet {//OVERVIEW: IntSets are unbounded, mutable sets of integers.

private Vector els; // the rep

//constructors

public IntSet () {//EFFECTS: Initializes this to be emptyels = new Vector(); }

//methods

public void insert (int x) {//MODIFIES: this//EFFECTS: Adds x to the elements of this.Integer y = new Integer(x);if (getIndex(y) < 0) els.add(y); }

public void remove (int x) {//MODIFIES: this//EFFECTS: Removes x from this.int i = getIndex(new Integer(x));if (i < 0) return;els.set(i, els.lastElement());els.remove(els.size() - 1); }

public boolean isIn (int x) {//EFFECTS: Returns true if x is in this else returns false.return getIndex(new Integer(x)) }

(Continued)

Page 34: Abstraction, Specification and Verification. Comp 302, Spring 2005 2 Abstraction Hiding or overlooking detail that is not relevant for the task at hand

Comp 302, Spring 200534

private int getIndex (Integer x) {//EFFECTS: If x is in this returns index where

//x appears else returns -1.for (int i = 0; i < els.size(); i++)

if (x.equals(els.get(i))) return i;return -1; }

public int size () {//EFFECTS: Returns the cardinality of this.return els.size(); }

public int choose () throws EmptyException {//EFFECTS: If this is empty throws EmptyException else //returns an

arbitrary element of this.if(els.size() == 0) throw new

EmptyException(“IntSet.choose”);return els.lastElement(); }

}