Assertions. Assertions - Example

Similar documents
References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

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

CSC Advanced Object Oriented Programming, Spring Specification

17. Assertions. Outline. Built-in tests. Built-in tests 3/29/11. Jelle Slowack, Bart Smets, Glenn Van Loon, Tom Verheyen

17. Assertions. Jelle Slowack, Bart Smets, Glenn Van Loon, Tom Verheyen

Assertions, pre/postconditions

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

Adding Contracts to C#

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012

Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen

CSE 331. Programming by contract: pre/post conditions; Javadoc

Software Architecture. Abstract Data Types

MSO Lecture Design by Contract"

Software Engineering Testing and Debugging Testing

What This Course Is About Design-by-Contract (DbC)

Self-checking software insert specifications about the intent of a system

AXIOMS OF AN IMPERATIVE LANGUAGE PARTIAL CORRECTNESS WEAK AND STRONG CONDITIONS. THE AXIOM FOR nop

Catching Defects: Design or Implementation Phase? Design-by-Contract (Dbc) Test-Driven Development (TDD) Motivation of this Course

Software Engineering

Design by Contract in Eiffel

Chapter 1: Programming Principles

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

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

Specifications. CSE 331 Spring 2010

JAVA BASICS II. Example: FIFO

Software Development. Modular Design and Algorithm Analysis

CS 617 Object Oriented Systems Lecture 3 Object Abstractions, Encapsulation, Abstract Data Types 3:30-5:00pm Thu, Jan 10

Java: advanced object-oriented features

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

3. Design by Contract

Chapter 1: Principles of Programming and Software Engineering

A Practical Approach to Programming With Assertions

Softwaretechnik. Lecture 08: Testing and Debugging Overview. Peter Thiemann SS University of Freiburg, Germany

Design by Contract: An Overview

Softwaretechnik. Lecture 08: Testing and Debugging Overview. Peter Thiemann SS University of Freiburg, Germany

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

OO Design Principles

Testing and Debugging

Outline for Today CSE 142. CSE142 Wi03 G-1. withdraw Method for BankAccount. Class Invariants

Lecture 10 Design by Contract

Program Verification using Templates over Predicate Abstraction. Saurabh Srivastava and Sumit Gulwani

The Eiffel language. Slides partly based on :

Announcements. Specifications. Outline. Specifications. HW1 is due Thursday at 1:59:59 pm

A comparative study of Programming by Contract and Programming with Exceptions

Object Oriented Program Correctness with OOSimL

Outline. iterator review iterator implementation the Java foreach statement testing

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

Object-Oriented Design

Test-Driven Development (TDD)

Lecture 9 / Tutorial 8 Software Contracts

Programming with Contracts. Juan Pablo Galeotti, Alessandra Gorla Saarland University, Germany

Eiffel: Analysis, Design and Programming. ETH Zurich, September-December Exception handling

Design-by-Contract (Dbc) Test-Driven Development (TDD)

Automatic Testing Based on Design by Contract

CS 520 Theory and Practice of Software Engineering Fall 2018

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

CSE 331 Final Exam 3/16/15 Sample Solution

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

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

Violations of the contract are exceptions, and are usually handled by special language constructs. Design by contract

Object-Oriented Design

6.170 Lecture 6 Procedure specifications MIT EECS

Program Verification (6EC version only)

Assignment 2 - Specifications and Modeling

Fun facts about recursion

Exceptions and assertions

Software Architecture. Abstract Data Types

Abstraction and Specification

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

High Quality Java Code: Contracts & Assertions

Automatic Verification of Computer Programs

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Conformance. Object-Oriented Programming Spring 2015

Lecture 4 Specifications

With the popularity of the Web and the

An Annotated Language

6.170 Recitation #5: Subtypes and Inheritance

CSE 331 Midterm Exam Sample Solution 2/18/15

Comparing procedure specifications

Testing. Prof. Clarkson Fall Today s music: Wrecking Ball by Miley Cyrus

Use of Generic Parameters Iterator and Singleton Patterns

Integrating verification in programming languages

Lecture 5 Representation Invariants

Lecture 7: Data Abstractions

OOP Design by Contract. Carsten Schuermann Kasper Østerbye IT University Copenhagen

Announcements. Representation Invariants and Abstraction Functions. Announcements. Outline

Design Principles: Part 2

Motivation. Correct and maintainable software Cost effective software production Implicit assumptions easily broken

Generic Collection Class: Motivation (2) Use of Generic Parameters Iterator and Singleton Patterns

Outline. Design Principles: Part 2. e.g. Rectangles and Squares. The Liskov Substitution Principle (LSP) ENGI 5895: Software Design.

Universe Type System for Eiffel. Annetta Schaad

Unit Testing as Hypothesis Testing

Advanced JML Erik Poll Radboud University Nijmegen

CHAPTER 6 Design by Contract. Literature. When Design by Contract? Why Design By Contract?

Motivation State Machines

Subtypes and Subclasses

Review sheet for Final Exam (List of objectives for this course)

Client, Supplier, Contract in OOP (1) Design-by-Contract (Dbc) Test-Driven Development (TDD) Terminology: Contract, Client, Supplier

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

Transcription:

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 11/13/2003 1 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 11/13/2003 2 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]; Implements the assertion //Assertion: this method returns the number of elements on the s tack public int size() { return top; Documents the routine 11/13/2003 3 1

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 11/13/2003 4 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) 11/13/2003 5 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 11/13/2003 6 2

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 11/13/2003 7 Preconditions public class BankAccount { public void deposit (float amount) {... Precondition is invalid: no way of verifying the precondition from the current state of the object //Pre-condition: amount <= current balance public void withdraw (float amount) {... This assumes that there is no method to return current balance. 11/13/2003 8 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 11/13/2003 9 3

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 11/13/2003 10 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. 11/13/2003 11 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. 11/13/2003 12 4

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; // Pre-condition: <none> // Post-condition: The capacity of // the stack is returned public int capacity() { return capacity;... Example showing a pre-condition, post-condition, and invariant. 11/13/2003 None of the assertions are checked at runtime. 13 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 precondition) than one that accepts any real number. The weakest pre- or post-condition is no pre- or post-condition at all. 11/13/2003 14 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 11/13/2003 15 5

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 11/13/2003 16 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. 11/13/2003 17 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 postcondition 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. 11/13/2003 18 6

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 postconditions should be weak enough to allow flexibility, but not too strong or too weak that it places an unreasonable burden on the client. 11/13/2003 19 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. 11/13/2003 20 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. 11/13/2003 21 7

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. 11/13/2003 22 8