Reasoning and Design (and Assertions). How to Design Your Code The hard way: Just start coding. When something doesn’t work, code some more! The easier.

Slides:



Advertisements
Similar presentations
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
Advertisements

Automated Theorem Proving Lecture 1. Program verification is undecidable! Given program P and specification S, does P satisfy S?
Identity and Equality Based on material by Michael Ernst, University of Washington.
Reasoning About Code; Hoare Logic, continued
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 6: Reasoning about Data Abstractions.
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION ABSTRACT DATA TYPES II Autumn 2011.
Abstraction Functions. Announcements Exam 1 on Tuesday March 3 rd Closed book/phone/laptop 2 cheat pages allowed (handwritten or typed) 1 double-sided.
OOP #10: Correctness Fritz Henglein. Wrap-up: Types A type is a collection of objects with common behavior (operations and properties). (Abstract) types.
CSE 331 Software Design & Implementation Dan Grossman Fall 2014 Data Abstraction: Abstract Data Types (ADTs) (Based on slides by Mike Ernst, David Notkin,
Slides by Vinod Rathnam with material from Alex Mariakakis Kellen Donohue, David Mailhot, and Hal Perkins Midterm Review.
Computer Science 340 Software Design & Testing Design By Contract.
Cs2220: Engineering Software Class 8: Implementing Data Abstractions Fall 2010 University of Virginia David Evans.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Cs205: engineering software university of virginia fall 2006 Data Abstraction David Evans
Exceptions and assertions CSE 331 University of Washington.
Reasoning about programs March CSE 403, Winter 2011, Brun.
Type Abstraction Liskov, Chapter 7. 2 Liskov Substitution Principle In any client code, if the supertype object is substituted by a subtype object, the.
Data Abstractions EECE 310: Software Engineering.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Abstract Data Types – Examples / Summary (Based on slides by Mike Ernst and David Notkin)
Type Abstraction SWE Spring October 05Kaushik, Ammann Substitution Principle “In any client code, if supertype object is substituted.
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Debugging COMP T1.
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
Data Abstraction SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Understanding ADTs CSE 331 University of Washington.
Representation invariants and abstraction functions CSE 331 UW CSE.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
CSE 331 Software Design & Implementation Dan Grossman Fall 2014 Abstraction Functions (Based on slides by Mike Ernst, David Notkin, Hal Perkins)
Iteration Abstraction SWE Software Construction Fall 2009.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 7: A Tale of Two Graphs (and.
Concurrent Programming Acknowledgements: Some slides adapted from David Evans, U. Virginia.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 6 Representation Invariants.
Representation Invariants and Abstraction Functions.
Exceptions and Testing. Review Problems: IntMap Specification The Overview: /** An IntMap is a mapping from integers to integers. * It implements a subset.
Testing (final thoughts). equals() and hashCode() Important when using Hash-based containers class Duration { public final int min; public final int sec;
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
Slides by Alex Mariakakis Section 5: Midterm Review.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Data Abstraction: Abstract Data Types (ADTs) (Based on slides by Mike Ernst and David.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 17 – Specifications, error checking & assert.
Winter 2006CISC121 - Prof. McLeod1 Stuff Midterm exam in JEF234 on March 9th from 7- 9pm.
EECE 310: Software Engineering
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation
CSE 374 Programming Concepts & Tools
CSE 331 Software Design and Implementation
Reasoning About Code.
Reasoning about code CSE 331 University of Washington.
CSE 143 Error Handling [Section 2.8] 3/30/98 CSE 143.
Type Abstraction SWE Spring 2009.
CSE 331 Software Design and Implementation
Representation Invariants and Abstraction Functions
Abstraction functions, Reasoning About ADTs
Specifications, conclusion. Abstract Data Types (ADTs)
Exam 1 Review.
Section 6: Midterm Review
Type Abstraction Liskov, Chapter 7.
Equality, conclusion Based on material by Michael Ernst, University of Washington.
Data Abstraction David Evans cs205: engineering software
SWE 619 Software Construction Last Modified, Fall 2015 Paul Ammann
Reasoning About ADTs, Assertions and Exceptions
Lecture 4: Data Abstraction CS201j: Engineering Software
EECE 310: Software Engineering
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Computer Science 340 Software Design & Testing
Type Abstraction SWE Spring 2013.
Software Specifications
Presentation transcript:

Reasoning and Design (and Assertions)

How to Design Your Code The hard way: Just start coding. When something doesn’t work, code some more! The easier way: Plan carefully Write specs, rep invariants, abstraction functions Write tests (first!), reason about code, refactor Less apparent progress at first, but faster completion times, better product, less frustration 2 Fall 15 CSCI 2600, A Milanova (based on a slide by Michael Ernst)

How to Verify Your Code The hard way: just coding, try some inputs An easier way: systematic testing Black-box testing techniques (more on this later) High white-box coverage (more on this later) JUnit framework Also: reasoning, complementary to testing Prove that code is correct Implementation satisfies specification Rep invariant is preserved 3

Uses of Reasoning Goal: show that code is correct Verify that the implementation satisfies its specification. This is difficult! Forward reasoning: show that if precondition holds, postcondition holds Backward reasoning: compute weakest precondition, then show stated precondition implies the weakest precondition Today: prove (using informal manual proofs) that rep invariant holds. This is sometimes easy, sometimes hard… 4

Goal: Show that Rep Invariant Is Satisfied Testing Choose representative objects and check rep Problem: it is impossible to exhaustively test, therefore, we have to choose well Reasoning Prove that all objects satisfy rep invariant Sometimes easier than testing, sometimes harder You should know how to use it appropriately Why not always leave checkRep() in code? 5

Verify that Rep Invariant Is Satisfied We have infinitely many objects, but limited number of operations How do we prove all objects satisfy rep invariant? Induction! Consider all ways to make a new object Constructors Producers All ways to modify an existing object Mutators Observers, producers. Why do we include these? Fall 15 CSCI 2600, A Milanova 6

Benevolent Side Effects in Observers An implementation of observer IntSet.contains : boolean contains(int x) { int i = data.indexOf(x); if (i == -1) return false; // move-to front optimization // speeds up repeated membership tests Integer y = data.elementAt(0); data.set(0,x); data.set(i,y); return true; } Mutates rep (even though it does not change abstract value), must show rep invariant still holds! 7

Ways to Make New Objects Fall 15 CSCI 2600, A Milanova (based on a slide by Mike Ernst) 8 a = constructor b = a.producera’ = a.mutatora’’ = a.observer c = b.producerb’ = b.mutatorb’’ = b.observer … Infinitely many objects but limited number of operations!

Induction Proving facts about infinitely many objects Base step Prove rep invariant holds on exit of constructor Inductive step Assume rep invariant holds on entry of method Then prove that rep invariant holds on exit Intuitively: there is no way to make an object, for which the rep invariant does not hold Remember, our proofs are informal Fall 15 CSCI 2600, A Milanova (based on slide by Mike Ernst) 9

The IntSet ADT /** Overview: An IntSet is a mutable set * of integers. E.g., { x 1, x 2, … x n }, {}. * There are no duplicates in the set. */ // effects: makes a new empty IntSet public IntSet() // modifies: this // effects: this post = this pre U { x } public void add(int x) // modifies: this // effects: this post = this pre - { x } public void remove(int x) // returns: (x in this) public boolean contains(int x) // reruns: cardinality of this public int size() 10

Implementation of IntSet class IntSet { // Rep invariant: // data has no nulls and no duplicates private List data; public IntSet() { data = new ArrayList (); } public void add(int x) { if (!contains(x)) data.add(x); } public void remove(int x) { data.remove(new Integer(x)); } public boolean contains(int x) { return data.contains(x); } 11 Fall 15 CSCI 2600, A Milanova

Proof. IntSet Satisfies Rep Invariant Rep invariant: data has no nulls and no duplicates Base case: constructor public IntSet() { data = new ArrayList (); } Rep invariant trivially holds Inductive step: for each method Assume rep invariant holds on entry Prove rep invariant holds on exit Fall 15 CSCI 2600, A Milanova 12

Inductive Step, contains Rep invariant: data has no nulls and no duplicates public boolean contains(int x) { return data.contains(x); } List.contains does not change data, so neither does IntSet.contains Therefore, rep invariant is preserved. Why do we even need to check contains ? Fall 15 CSCI 2600, A Milanova 13

contains with Benevolent Side Effects An implementation of observer IntSet.contains : boolean contains(int x) { int i = data.indexOf(x); if (i == -1) return false; // move-to front optimization // speeds up repeated membership tests Integer y = data.elementAt(0); data.set(0,x); data.set(i,y); return true; } We swapped elements of data at positions i and 0. If there were no duplicates and no nulls on entry, there are no duplicates and no nulls on exit 14

Inductive Step, remove Rep invariant: data has no nulls and no duplicates public void remove(int x) { data.remove(new Integer(x)); } ArrayList.remove has two behaviors Leaves data unchanged Removes an element Only addition can violate rep invariant Therefore, rep invariant is preserved Fall 15 CSCI 2600, A Milanova 15

Inductive Step, add Rep invariant: data has no nulls and no duplicates public void add(int x) { if (!contains(x)) data.add(x); } Case 1: x in data pre data is unchanged, thus rep invariant is preserved Case 2: x is not in data pre New element is not null or a duplicate, thus rep invariant holds at exit 16 Fall 15 CSCI 2600, A Milanova

Reasoning About Rep Invariant Inductive step must consider all possible changes to the rep Including representation exposure! If the proof does not account for representation exposure, then it is invalid! Exposure of immutable rep is OK. Fall 15 CSCI 2600, A Milanova 17

Review Problem: Willy’s IntStack class IntStack { // Rep invariant: |theRep| = size // and theRep.keySet = {i | 1 ≤ i ≤ size} private IntMap theRep = new IntMap(); private int size = 0; public void push(int val) { size = size+1; theRep.put(size,val); } public int pop() { int val = theRep.get(size); theRep.remove(size); size = size–1; return val; } 18

Review Problem: Willy’s IntStack Base case Prove rep invariant holds on exit of constructor Inductive step Prove that if rep invariant holds on entry of method, it holds on exit of method push Pop For brevity, ignore popping an empty stack Fall 15 CSCI 2600, A Milanova 19

Practice Defensive Programming Check Precondition Postcondition Rep invariant Other properties we know must hold Check statically via reasoning “Statically” means before execution Works in simpler cases (the examples we saw), can be difficult in general Motivates us to simplify and/or decompose our code! 20

Practice Defensive Programming Check dynamically via assertions What do we mean by “dynamically”? At run time Assertions, supported by Java since 1.4 assert index >= 0; assert coeffs.length-1 == degree : “Bad rep” assert coeffs[degree] != 0 : “Bad rep” Write assertions, as you write code Aside: not to be confused with JUnit method such as assertEquals! 21 Fall 15 CSCI 2600, A Milanova

Assertions java runs with assertions disabled (default) java –ea runs Java with assertions enabled Always enable assertions during development. Turn off in rare circumstances assert (index >= 0) && (index < names.length); Fall 15 CSCI 2600, A Milanova 22 If assertion fails, program exits: Exception in thread "main" java.lang.AssertionError at Main.main(Main.java:34)

When NOT to Use Assertions Useless: x = y+1; assert x == y+1; When there are side effects assert list.remove(x); // Better: boolean found = list.remove(x); assert found; How can you test at runtime whether assertions are enabled? 23