Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.

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

Design by Contract.
Carlos D. Rivera February 28, 2007 Design-by-Contract.
Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy Eivind J. Nordby.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION DEBUGGING Autumn 2011 Bug-Date: Sept 9, 1947.
Design by Contract. Design by contract is the process of developing software based on the notion of contracts between objects, which are expressed as.
Chair of Software Engineering OOSC - Summer Semester Object-Oriented Software Construction Bertrand Meyer.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Error Management with Design Contracts Karlstad University Computer Science Error Management with Design Contracts Eivind J. Nordby, Martin Blom, Anna.
1 Design by Contract Building Reliable Software. 2 Software Correctness Correctness is a relative notion  A program is correct with respect to its specification.
Chapter 8 Designing Classes. Assignment Chapter 9 Review Exercises (Written)  R8.1 – 8.3, 8.5 – 8.7, 8. 10, 8.11, 8.13, 8.15, 8.19, 8.20 Due Friday,
Object Oriented Design An object combines data and operations on that data (object is an instance of class) data: class variables operations: methods Three.
On the Relation between Design Contracts and Errors Karlstad University Computer Science On the Relation Between Design Contracts and Errors A Software.
Chair of Software Engineering ATOT - Lecture 12, 12 May Advanced Topics in Object Technology Bertrand Meyer.
Static and Dynamic Contract Verifiers For Java Hongming Liu.
OOP #10: Correctness Fritz Henglein. Wrap-up: Types A type is a collection of objects with common behavior (operations and properties). (Abstract) types.
Eiffel Language and Design by Contract Contract –An agreement between the client and the supplier Characteristics –Expects some benefits and is prepared.
Adding Contracts to Ada Ehud Lamm Adding Design By Contract to Ada.
1 © Wolfgang Pelz Design by Contract Design by Contract™ Based on material drawn from: Bertrand.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
Computer Science 340 Software Design & Testing Design By Contract.
Dr. Pedro Mejia Alvarez Software Testing Slide 1 Software Testing: Building Test Cases.
Ranga Rodrigo. Class is central to object oriented programming.
Introduction Ellen Walker CPSC 201 Data Structures Hiram College.
1 Debugging and Testing Overview Defensive Programming The goal is to prevent failures Debugging The goal is to find cause of failures and fix it Testing.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Contract based programming Using pre- and post-conditions, and object invariants Contract based programming1.
Design by Contract in Java Concept and Comparison.
SWE 619 © Paul Ammann Procedural Abstraction and Design by Contract Paul Ammann Information & Software Engineering SWE 619 Software Construction cs.gmu.edu/~pammann/
111 Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract,
© Paul Ammann, 2008 Design by Contract Paul Ammann CS/SWE 332.
Design by Contract Ranga Rodrigo based on Mark Priestley's Lectures.
Pre- and postconditions, Using assertions and exceptions 1 Pre- and postconditions Using assertions and exceptions.
Protocols Software Engineering II Wirfs Brock et al, Designing Object-Oriented Software, Prentice Hall, Mitchell, R., and McKim, Design by Contract,
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Debugging COMP T1.
Class Design I Class Contracts Readings: 2 nd Ed: Section 9.5, Advanced Topic nd Ed: Section 8.5, Advanced Topic 8.2 Some ideas come from: “Practical.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Defensive Programming CNS 3370 Copyright 2003, Fresh Sources, Inc.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
1 Phase Testing. Janice Regan, For each group of units Overview of Implementation phase Create Class Skeletons Define Implementation Plan (+ determine.
DBC NOTES. Design By Contract l A contract carries mutual obligations and benefits. l The client should only call a routine when the routine’s pre-condition.
1 Exceptions When the Contract is Broken. 2 Definitions A routine call succeeds if it terminates its execution in a state satisfying its contract A routine.
Object Design More Design Patterns Object Constraint Language Object Design Specifying Interfaces Review Exam 2 CEN 4010 Class 18 – 11/03.
Design by Contract. The Goal Ensure the correctness of our software (correctness) Recover when it is not correct anyway (robustness) Correctness: Assertions.
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 17 – Specifications, error checking & assert.
Class Invariants Class invariants are logical conditions to ensure the correct working of a class. Class invariants must hold true when an object is created,
Design by Contract Jim Fawcett CSE784 – Software Studio
Design by Contract Jim Fawcett CSE784 – Software Studio
Used to help understand requirements more completely
Data Abstraction: The Walls
CSE 374 Programming Concepts & Tools
CSE 143 Error Handling [Section 2.8] 3/30/98 CSE 143.
Design by Contract in Python: Present and Future Aaron Bingham
CS313D: Advanced Programming Language
Design by Contract Fall 2016 Version.
Preconditions, Postconditions & Assertions
Object initialization: constructors
Slides by Steve Armstrong LeTourneau University Longview, TX
CSC 143 Error Handling Kinds of errors: invalid input vs programming bugs How to handle: Bugs: use assert to trap during testing Bad data: should never.
Design by contract Object-Oriented Software Construction by Bertrand Meyer, Prentice Hall The presence of a precondition or postcondition in a routine.
Semantics In Text: Chapter 3.
Design by contract Object-Oriented Software Construction by Bertrand Meyer, Prentice Hall The presence of a precondition or postcondition in a routine.
Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract, Computer,
Go to pollev.com/cse143.
Computer Science 340 Software Design & Testing
Software Specifications
Design Contracts and Errors A Software Development Strategy
Presentation transcript:

Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019

Assertions Statements about input to a routine or state of a class Have two primary roles As documentation, they express valid ways of using a routine or class When implemented, help to isolate runtime errors 4/25/2019

Assertions - Example public class SimpleStack { //Assertion: this method should only be called when the stack is not empty public int pop() { if (size() <= 0) { throw new Stackexception(“pop() called on an empty stack”); } return data[--top]; //Assertion: this method returns the number of elements on the stack public int size() { return top; … Implements the assertion Documents the routine 4/25/2019

Assertions Assertions are an unambiguous way to document a routine; thus, assertions can be checked at runtime Originally part of Java (then called Oak), but omitted from spec in order to meet deadline Popularized by Bertrand Meyer(1992) and directly supported by the language Eiffel. Boolean expressions attached to methods Test the state of an object at various points during execution, ensuring that certain conditions are satisfied Automatically inherited and enforced by subclasses even when actual methods are overridden 4/25/2019

Assertions Meyer proposed idea of Design by Contract assertions form a contract between client and service provider software contracts are specified by pre- and post-conditions and class invariants Failure to meet the contract terms indicates a bug (fault) 4/25/2019

Design by Contract Violation of a pre-condition means the contract was broken by the client The “contractor” does not have to fulfill its part of the contract, but may raise an exception to signal the fault Violation of a post-condition indicates the presence of a bug in the implementation of the routine 4/25/2019

Preconditions A condition that must be true before a method executes Documents the assumptions of the author of the routine Clients of the method are responsible for ensuring the preconditions are met on entrance to the method; if they are not, then the method behavior is undefined Must be verifiable by the client using the public interface of the class that contains the method Client should be able to verify the preconditions from the current state of the object 4/25/2019

Preconditions public class BankAccount { public void deposit (float amount) { . . . } //Pre-condition: amount <= current balance public void withdraw (float amount) { Precondition is invalid: no way of verifying the precondition from the current state of the object This assumes that there is no method to return current balance. 4/25/2019

Postconditions Condition that will be true after a method executes Author of the method is responsible for ensuring the method’s post-conditions are met Author of the method must only ensure the post-conditions of a method are true when the pre-conditions of the method have been met 4/25/2019

Postconditions May be expressed in terms of the public interface and/or the private implementation Post-condition expressed in terms of the public interface is of interest to clients Post-condition expressed in terms of the private interface is of interest to programmers maintaining the routine 4/25/2019

Invariants An invariant is an expression about an object that must be true when the object is in a stable state. An object is in a stable state after construction and between public method calls. Notice that pre- and post-conditions are statements about the behavior of a method, while invariants are statements about the state of an object. Because invariants are true after construction and between public method calls, the class is responsible for maintaining invariants. 4/25/2019

Invariants Invariants are also expressed in terms of the public interface and/or the private implementation Invariants are true for the current public methods of a class and any new methods that are added in the future If a new public routine is allowed to violate an invariant, it may leave the object in an unstable state for another public method. 4/25/2019

Example // Invariant: 0 <= size() <= capacity() public class SimpleStack { // Pre-condition: The stack is not // empty // Post-condition: The last integer // pushed onto the stack is // returned. The stack size // is reduced by one // element. public int pop() { return data[--top]; } // Pre-condition: <none> // Post-condition: The number of // elements in the stack are returned public int size() { return top; } // Post-condition: The capacity of // the stack is returned public int capacity() { return capacity; ... Example showing a pre-condition, post-condition, and invariant. None of the assertions are checked at runtime. 4/25/2019

Pre- and Post-condition strength The strength of a pre- or post-condition is a measure of its restrictiveness. A strong pre- or post-condition is more restrictive than a weaker one. For example, a function that only accepts integers is more restrictive (has a stronger pre-condition) than one that accepts any real number. The weakest pre- or post-condition is no pre- or post-condition at all. 4/25/2019

Example 1: Binary Search public class Arrays { . . . // Pre-condition: the array 'a' is sorted in ascending //order // Post-condition: Returns the index of the first element in // array 'a' equal to 'key' if one exists, otherwise returns // -1 as an indication that the parameter 'key' is not an // element of the array. public static int binarySearch(int[] a, int key); } Duplicates allowed 4/25/2019

Example 2: Binary Search A stronger pre-condition is one that is more restrictive or narrows the range of acceptable inputs. The original definition of the binary search method allowed duplicate elements. The following is a stronger pre-condition: // Pre-condition: the array 'a' is sorted in // ascending order, and doesn't contain any // duplicate elements 4/25/2019

Example 3 : Binary Search We could weaken the post-condition of the original definition by allowing the routine to return any negative number if the key is not found: // Post-condition: Returns the index of the first // element in array 'a' equal to 'key' if one exists, // otherwise returns any negative number as an // indication that the parameter 'key' is not an // element of the array. This post-condition is weaker because there is a greater number of outputs that are valid. 4/25/2019

Strength of Assertions Reason for making the pre-condition stronger or the post-condition weaker than what the routine would suggest: Flexibility. A stronger pre-condition and a weaker post-condition give you the flexibility to change the implementation in the future without changing the interface and possibly breaking clients. Flexibility comes at the expense of the client. The client now has to work harder to maintain the pre-condition and to be prepared for the post-condition. 4/25/2019

Strength of Assertions When defining the pre- and post-conditions for a routine, need balance. Consider how much implementation flexibility is needed in the routine and how much additional burden it is for the client for a given amount of flexibility. Pre-conditions should be strong enough and post-conditions should be weak enough to allow flexibility, but not too strong or too weak that it places an unreasonable burden on the client. 4/25/2019

Benefits of Assertion Checking Assertion checking at runtime is a debugging aid. The primary purpose of assertion checking at runtime is to identify and isolate runtime errors. Finding a runtime error in a large software system is difficult. The difficulty grows more than linearly with the size of the system. For example, if the size of a system doubles it will be more than twice as hard to find a runtime error. 4/25/2019

Benefits of Assertion Checking Part of the problem is that the fault (such as a wrong number on a report) is often a long distance from the defect (such as not reading the last record during the input loop). distance can be the number of instructions executed at runtime or physical distance between static instructions in the written program. The greater the distance between a fault and the defect the harder it will be to find a defect that caused a specific fault. The traditional way of debugging a problem is to start at the fault and work your way back to the defect. Because of conditional branching in code, as you work backwards the number of source branches you need to consider grows exponentially. 4/25/2019

Benefits of Assertion Checking In this conceptual image, there are 10 potential source paths for the visible fault. Assertion checking helps to identify errors early, closer to the defect that caused them. Assertion checking may identify errors that would have otherwise gone undetected. 4/25/2019