Representation invariants and abstraction functions CSE 331 UW CSE

Similar documents
Implementing an ADT: Representation invariants

Lecture 5 Representation Invariants

Understanding an ADT implementation: Abstraction functions

CSE 331 Software Design & Implementation

Lecture 7 Abstraction Functions

Representation Invariants and Abstraction Functions

Announcements. Representation Invariants and Abstraction Functions. Announcements. Outline

CSE 331 Midterm Exam Sample Solution 2/13/12

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Programming Languages Seminar. Lecture in the subject of. Yair Moshe

CSE 331 Midterm Exam 2/13/12

Lecture 12: Abstraction Functions

Representation Invariant, Abstraction Function

Sec$on 2: Specifica)on, ADTs, RI WITH MATERIAL FROM MANY

Abstraction Functions Lecture 9 Fall 2005

CSE wi Midterm Exam 2/8/18 Sample Solution

Refresher: Interface Specifications. ADT Documentation. Set Represented as an Array. Representation Invariant, Abstraction Function

Lecture 7: Data Abstractions

CSE331 Autumn 2011 Midterm Examination October 28, 2011

Solutions to Quiz 1 (October 19, 2015)

CSE331 Winter 2014, Midterm Examination February 12, 2014

CSE wi Midterm Exam 2/8/18. Name UW ID #

Abstraction and Specification

CSE 331 Midterm Exam Sample Solution 2/18/15

6.005 Elements of Software Construction Fall 2008

Exam 1 CSCI 2600 Principles of Software October 6, 2015

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Reasoning about programs

Last time. Reasoning about programs. Coming up. Project Final Presentations. This Thursday, Nov 30: 4 th in-class exercise

CSE 331 Midterm Exam 11/9/15 Sample Solution

CSE 331 Winter 2016 Midterm Solution

Exam 1 CSCI 2600 Principles of Software October 6, 2015

Assertions, pre/postconditions

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

CSE 331 Final Exam 3/16/15 Sample Solution

So far. Specifications, conclusion. Abstract Data Types (ADTs) Comparison by Logical Formulas. Outline

Computer Science 136. Midterm Examination

Testing. UW CSE 160 Winter 2016

Regression testing. Whenever you find a bug. Why is this a good idea?

Steps for project success. git status. Milestones. Deliverables. Homework 1 submitted Homework 2 will be posted October 26.

Lecture Notes on Contracts

Warmup. A programmer s roommate tells him, Would you mind going to the store and picking up a loaf of bread. Also, if they have eggs, get a dozen.

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.

Abstraction Functions and Representation Invariants

Solutions to Quiz 1 (March 14, 2016)

Handout 9: Imperative Programs and State

6.170 Lecture 7 Abstract Data Types MIT EECS

Warmup. A programmer s roommate tells him, Would you mind going to the store and picking up a loaf of bread. Also, if they have eggs, get a dozen.

Lecture 10 Notes Linked Lists

Top Down Design vs. Modularization

CSE 331 Software Design & Implementation

Solutions to Quiz 1 (March 22, 2019)

Comparing procedure specifications

CS 520 Theory and Practice of Software Engineering Fall 2018

L6: Abstract Data Types

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Exceptions and assertions

Concurrent Objects and Linearizability

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

OOPLs Semantic Foundations. Data Abstraction Foundation of OOPLs

Lecture Notes on Linear Search

3 ADT Implementation in Java

Introduction to Software Testing Chapter 4 Input Space Partition Testing

Assertions. Assertions - Example

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

n Specifying what each method does q Specify it in a comment before method's header n Precondition q Caller obligation n Postcondition

Chapter 4 Defining Classes I

CSE 331 Final Exam 6/5/17. Name UW ID#

3. Design by Contract

Recursively Enumerable Languages, Turing Machines, and Decidability

Classes, interfaces, & documentation. Review of basic building blocks

UC Santa Barbara. CS189A - Capstone. Christopher Kruegel Department of Computer Science UC Santa Barbara

Program Design with Abstract Data Types

Solutions to Quiz 1 (October 25, 2017)

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

CSE wi: Practice Midterm

6. Relational Algebra (Part II)

Input Space Partitioning

CSE331 Winter 2014, Midterm Examination February 12, 2014

CPS122 Lecture: Detailed Design and Implementation

Data Abstraction and Specification of ADTs

Solutions to Quiz 2 (December 3, 2018)

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore

Lecture 4: Procedure Specifications

CSE 331 Final Exam 12/14/15 Sample Solution. Question 1. (20 points, 1 each) Warmup. For each statement, circle T if it is true and F if it is false.

Testing, Debugging, and Verification

a correct statement? You need to know what the statement is supposed to do.

Another interface: Comparable

Lecture 8 Data Structures

Static Analysis in Practice

Advanced JML Erik Poll Radboud University Nijmegen

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

Announcements. Testing. Announcements. Announcements

Lecture 5 Abstract Data Types

Part II. Hoare Logic and Program Verification. Why specify programs? Specification and Verification. Code Verification. Why verify programs?

Assertions and Exceptions Lecture 11 Fall 2005

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Lecture 11: In-Place Sorting and Loop Invariants 10:00 AM, Feb 16, 2018

Java: advanced object-oriented features

Lecture 4 Searching Arrays

Transcription:

Representation invariants and abstraction functions CSE 331 UW CSE

ADTs and specifications Specification: only in terms of the abstraction Never mentions the representation An ADT is more than just a data structure data structure + a set of conventions Why do we need to relate the specification to the representation?

Connecting specifications and implementations Representation invariant: Object boolean Indicates whether a data structure is well-formed Defines the set of valid values of the data structure Abstraction function: Object abstract value What the data structure means(as an abstract value) How the data structure is to be interpreted How do you compute the inverse, abstract value Object?

A data abstraction is defined by a specification A collection of procedural abstractions Not a collection of procedures Together, these procedural abstractions provide A set of values Allthe ways of directly using that set of values Creating Manipulating Observing Creators and producers: make new values Mutators: change the value (but don t affect ==) Observers: allow one to tell values apart

Implementation of an ADT is provided by a class To implement a data abstraction Select the representation of instances, the rep Implement operations in terms of that rep Choose a representation so that It is possible to implement operations The most frequently used operations are efficient But which will these be? Abstraction allows the rep to change later

CharSetAbstraction // Overview: A CharSet is a finite mutable set of Characters // effects: creates a fresh, empty CharSet public CharSet ( ) // modifies: this // effects: this post = this pre U {c public void insert (Character c); // modifies: this // effects: this post = this pre - {c public void delete (Character c); // returns: (c this) public boolean member (Character c); // returns: cardinality of this public int size ( );

A CharSetimplementation. What client code will expose the error? class CharSet { private List<Character> elts = new ArrayList<Character>(); public void insert(character c) { elts.add(c); public void delete(character c) { elts.remove(c); CharSet s = new CharSet(); public boolean member(character Character c) { a return elts.contains(c); public int size() { return elts.size(); = new Character( a ); s.insert(a); s.insert(a); s.delete(a); if (s.member(a)) // print wrong ; else // print right ;

Where Is the Error? The answer to this question tells you what needs to be fixed Perhaps delete is wrong It should remove all occurrences Perhaps insert is wrong It should not insert a character that is already there How can we know? The representation invariant tells us

The representation invariant States data structure well-formedness Captures information that must be shared across implementations of multiple operations Write it this way: class CharSet { // Rep invariant: elts has no nulls and no duplicates private List<Character> elts; Or, if you are the pedantic sort: indices i of elts. elts.elementat(i) null indices i, j of elts. i j elts.elementat(i).equals(elts.elementat(j))

Now, we can locate the error // Rep invariant: // elts has no nulls and no duplicates public void insert(character c) { elts.add(c); public void delete(character c) { elts.remove(c);

Another rep invariant example class Account { private int balance; // history of all transactions private List<Transaction> transactions; // real-world constraints: balance 0 balance = Σ i transactions.get(i).amount // implementation-related constraints: transactions null no nulls in transactions

Listing the elements of a CharSet Consider adding the following method to CharSet // returns: a List containing the members of this public List<Character> getelts(); Consider this implementation: // Rep invariant: elts has no nulls and no duplicates public List<Character> getelts() { return elts; Does the implementation of getelts preserve the rep invariant? sort of

Representation exposure Consider the client code (outside the CharSet implementation) CharSet s = new CharSet(); Character a = new Character( a ); s.insert(a); s.getelts().add(a); s.delete(a); if (s.member(a)) Representation exposure is external access to the rep Representation exposure is almost always evil If you do it, document why and how And feel guilty about it!

Ways to avoid rep exposure 1. Exploit immutability Character choose() { return elts.elementat(0); Character is immutable. 2. Make a copy List<Character> getelts() { return new ArrayList<Character>(elts); // or: return (ArrayList<Character>) elts.clone(); Mutating a copy doesn t affect the original. Don t forget to make a copy on the way in! 3. Make an immutable copy List<Character> getelts() { return Collections.unmodifiableList<Character>(elts); Client cannot mutate Still need to make a copy on the way in

Checking rep invariants Should code check that the rep invariant holds? Yes, if it s inexpensive Yes, for debugging (even when it s expensive) It s quite hard to justify turning the checking off Some private methods need not check (Why?)

Checking the rep invariant Rule of thumb: check on entry and on exit (why?) public void delete(character c) { checkrep(); elts.remove(c) // Is this guaranteed to get called? // See handouts for a less error-prone way to check at exit. checkrep(); /** Verify that elts contains no duplicates. */ private void checkrep() { for (int i = 0; i < elts.size(); i++) { assert elts.indexof(elts.elementat(i)) == i;

Practice defensive programming Assume that you will make mistakes Write and incorporate code designed to catch them On entry: Check rep invariant Check preconditions (requires clause) On exit: Check rep invariant Check postconditions Checking the rep invariant helps you discover errors Reasoning about the rep invariant helps you avoid errors Or prove that they do not exist! We will discuss such reasoning, later in the term

The rep invariant constrains structure, not meaning New implementation of insert that preserves the rep invariant: public void insert(character c) { Character cc = new Character(encrypt(c)); if (!elts.contains(cc)) elts.addelement(cc); public boolean member(character c) { return elts.contains(c); The program is still wrong Clients observe incorrect behavior What client code exposes the error? Where is the error? We must consider the meaning The abstraction function helps us CharSet s = new CharSet(); Character a = new Character( a )); s.insert(a); if (s.member(a)) // print right ; else // print wrong ;

Abstraction function: rep abstract value Theabstraction function maps the concrete representation to the abstract value it represents AF: Object abstract value AF(CharSetthis) = { c c is contained in this.elts set of Characters contained in this.elts Typically not executable The abstraction function lets us reason about behavior from the client perspective Our real goal is to satisfy the specification of insert: // modifies: this // effects: this post = this pre U {c public void insert (Character c); Once again we can place the blame Applying the abstraction function to the result of the call to insert yields AF(elts) U {encrypt( a ) What if we used this abstraction function? AF(this) = { c encrypt(c) is contained in this.elts AF(this) = { decrypt(c) c is contained in this.elts

Placing the blame Our real goal is to satisfy the specification of insert: // modifies: this // effects: this post = this pre U {c public void insert (Character c); The AF tells us what the rep means (and lets usplace the blame) AF(CharSetthis) = { c c is contained in this.elts Consider a call to insert: On entry, the meaning is AF(this pre ) elts pre On exit, the meaning is AF(this post ) = AF(this pre ) U{encrypt( a ) What if we used this abstraction function? AF(this) = { c encrypt(c) is contained in this.elts = { decrypt(c) c is contained in this.elts

Benevolent side effects Different implementation of member: boolean member(character c1) { a int i = elts.indexof(c1); if (i == -1) return false; // move-to-front optimization AF Character c2 = elts.elementat(0); elts.set(0, c1); elts.set(i, c2); op return true; Move-to-front speeds up repeated membership tests Mutates rep, but does not change abstract value AF maps both reps to the same abstract value AF r r

The abstraction function is a function Q: Why do we map concrete to abstract rather than vice versa? 1. It s not a function in the other direction. E.g., lists [a,b] and [b,a] each represent the set {a, b 2. It s not as useful in the other direction. Can construct objects via the provided operators

Writing an abstraction function The domain: all representations that satisfy the rep invariant The range: can be tricky to denote For mathematical entities like sets: easy For more complex abstractions: give them fields AF defines the value of each specification field For derived specification fields, see the handouts The overview section of the specification should provide a way of writing abstract values A printed representation is valuable for debugging

Summary Rep invariant Which concrete values represent abstract values Abstraction function For each concrete value, which abstract value it represents Together, they modularize the implementation Can examine operators one at a time Neither one is part of the abstraction (the ADT) In practice Always write a representation invariant Write an abstraction function when you need it Write an informal one for most non-trivial classes A formal one is harder to write and usually less useful