1 / 34

Abstraction, Specification and Verification

Abstraction, Specification and Verification. 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. Two Program Fragments. // search upwards found = false;

tawny
Télécharger la présentation

Abstraction, Specification and Verification

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Abstraction, Specification and Verification

  2. 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

  3. 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; }

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

  5. 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 +5 ; } else { return m*m + n*n; } }

  6. 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; } }

  7. Pre- and post- conditions 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 float 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; }

  8. 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.

  9. 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.

  10. 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

  11. 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

  12. Specifications of Classes visibility cname { //OVERVIEW: This clause defines the purpose of the class as a whole. visibility static p1 ... visibility static p2 ... }

  13. Example public 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, hashtable of students studentHash // 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]. }

  14. 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

  15. 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].

  16. The @modifies clause public 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

  17. 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.inpublic static finalInputStreamin 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 PrintStreamout 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)

  18. 3.4 Implementing Procedures: Example public 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 }

  19. 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); } …

  20. 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] = temp j--;i++; } else return j; } } }

  21. 3.4 Implementing Procedures public 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 v while (j < v.size()) if (!x.equals(v.get(j))) j++; else { v.set(j, v.lastElement()); v.remove(v.size()-1); } } } }

  22. Verifying Data Abstractions

  23. 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

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

  25. Specifications for Data Abstractions visibility 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 }

  26. Specification of IntSet (code filled in later) mutators observers public class IntSet { //OVERVİEW: IntSets are mutable, unbounded sets of integers //A typical IntSet is {x1,...,xn}. //constructors public IntSet ( ) //EFFECTS: Initialize this to be empty. (no need for MODIFIES clause) //methods public 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. }

  27. 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.

  28. public class Poly { //OVERVIEW: Polys are immutable polynomials with integer coefficients. //A typical Poly is c0 + c1x + c2x2 + ... + cnxn //constructors public 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. //methods public 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. }

  29. Using Data Abstractions public 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; }

  30. 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.

  31. 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

  32. 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

  33. public class IntSet { //OVERVIEW: IntSets are unbounded, mutable sets of integers. private Vector els; // the rep //constructors public IntSet () { //EFFECTS: Initializes this to be empty els = 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)

  34. 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(); } }

More Related