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

Similar documents
Assertions. Assertions - Example

Assertions, pre/postconditions

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

CSC Advanced Object Oriented Programming, Spring Specification

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

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

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

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

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

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

Java: advanced object-oriented features

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

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

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

Adding Contracts to C#

3. Design by Contract

Design by Contract in Eiffel

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

Exceptions and assertions

JAVA BASICS II. Example: FIFO

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

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

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

Outline. iterator review iterator implementation the Java foreach statement testing

CSE 331 Software Design & Implementation

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

Exception-Handling Overview

Designing Robust Classes

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

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

MSO Lecture Design by Contract"

Specifications. CSE 331 Spring 2010

Object Oriented Program Correctness with OOSimL

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

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

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

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

6.170 Lecture 6 Procedure specifications MIT EECS

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

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

Test-Driven Development (TDD)

Comparing procedure specifications

Chapter 1: Programming Principles

Software Engineering Testing and Debugging Testing

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

A Practical Approach to Programming With Assertions

A comparative study of Programming by Contract and Programming with Exceptions

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

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

Design by Contract: An Overview

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

Software Architecture. Abstract Data Types

Software Engineering

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

PROCESS DEVELOPMENT METHODOLOGY The development process of an API fits the most fundamental iterative code development

Introduction to Programming Using Java (98-388)

CS 3 Introduction to Software Engineering. 3: Exceptions

OO Design Principles

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Assertions and Exceptions Lecture 11 Fall 2005

EXCEPTION HANDLING. Summer 2018

CSE 331 Final Exam 3/16/15 Sample Solution

Dynamic Analysis Techniques Part 2

Software Development. Modular Design and Algorithm Analysis

Chapter 9. Software Testing

The Eiffel language. Slides partly based on :

Lecture 4: Procedure Specifications

Programming II (CS300)

Chapter 1: Principles of Programming and Software Engineering

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

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

Lecture 10 Design by Contract

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

Testing & Debugging TB-1

Assignment 2 - Specifications and Modeling

Chapter 4 Defining Classes I

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Symbolic Execution and Proof of Properties

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

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

hwu-logo.png 1 class Rational { 2 int numerator ; int denominator ; 4 public Rational ( int numerator, int denominator ) {

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

CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.

Specification tips and pitfalls

Code Contracts in C#

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Testing and Debugging

Object-Oriented Design

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

C#: advanced object-oriented features

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

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

High Quality Java Code: Contracts & Assertions

Programming II (CS300)

6.Introducing Classes 9. Exceptions

CS11 Advanced Java. Winter Lecture 2

Programming with assertions Oracle guidelines

Programming II (CS300)

Transcription:

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 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 10/14/2004 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 stack public int size() { return top; Documents the routine 10/14/2004 3

Assertions An unambiguous way to document a routine Can be checked at runtime Originally part of Java (then called Oak), but omitted from spec in order to meet deadline 10/14/2004 4

Assertions 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 10/14/2004 5

Design by Contract Meyer proposed this idea: 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) 10/14/2004 6

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 10/14/2004 7

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 10/14/2004 8

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. 10/14/2004 9

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 10/14/2004 10

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 10/14/2004 11

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. pre- and post-conditions are statements about behavior of a method invariants are statements about state of an object. Because invariants are true after construction and between public method calls, the class is responsible for maintaining invariants. 10/14/2004 12

Invariants Also expressed in terms of the public interface and/or the private implementation 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. 10/14/2004 13

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. None of the assertions are checked at runtime. 10/14/2004 14

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. 10/14/2004 15

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. Duplicates allowed public static int binarysearch(int[] a, int key);... 10/14/2004 16

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 10/14/2004 17

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. 10/14/2004 18

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. 10/14/2004 19

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. 10/14/2004 20

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. 10/14/2004 21

Benefits of Assertion Checking 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. 10/14/2004 22

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. 10/14/2004 23

Mechanics of Assertion Checking There are no rigid rules for writing assertion checks. For example, the following is acceptable: // Pre-condition: a >= 0 public static double sqrt(double a) { if (a < 0) System.exit(0);... but not much better than no check at all, because it doesn't give any indication about the assertion that failed. 10/14/2004 24

Mechanics of Assertion Checking We can improve the previous example by adding an error message: // Pre-condition: a >= 0 public static double sqrt(double a) { if (a < 0) { System.out.println("Pre-condition failure in sqrt()."); System.out.println("Input is < 0."); System.exit(0);... Adding an error message makes it easier to find the problem that ended the program abnormally, but still may make it hard to locate the problem in a large program. 10/14/2004 25

Mechanics of Assertion Checking Another method to signal and find an error is to print a stack trace: // Pre-condition: a >= 0 public static double sqrt(double a) { if (a < 0) { new Throwable().printStackTrace(); System.exit(0);... The new statement creates but doesn't throw an exception. The exception is created in order to have access to the nonstatic method printstacktrace(). 10/14/2004 26

Mechanics of Assertion Checking Throwing an exception is an acceptable way of signaling an assertion violation; however, you should never throw a checked exception: // Pre-condition: a >= 0 public static double sqrt(double a) throws Exception { if (a < 0) { // Wrong way to signal an assertion violation throw new Exception("Pre-condition failure. Input is < 0.");... Throwing a checked exception forces the caller to check for the exception. Assertion code shouldn't require any modifications to the "real" code. Here "real" refers to the client code implementing the specifications of the application. 10/14/2004 27

Mechanics of Assertion Checking If assertion checking code throws an exception, it should be an unchecked exception: // Pre-condition: a >= 0 public static double sqrt(double a) { if (a < 0) { // Correct way to signal an assertion violation //with an exception throw new Error("Pre-condition failure. Input is < 0.");... 10/14/2004 28

Assertions in Java The Java API 1.4 now includes assertions. Here is what Sun says: Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors 10/14/2004 29

Java Assertions java.lang Class AssertionError java.lang.object +--java.lang.throwable +-- java.lang.error +--java.lang.assertionerror All Implemented Interfaces: Serializable 10/14/2004 30

Two forms of assertion statement simpler form: assert Expression1 ; boolean expression. where Expression1 is a When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message. second form: assert Expression1 : Expression2 ; where: Expression1 is a boolean expression. Expression2 is an expression that has a value. (cannot be an invocation of a method that is declared void.) 10/14/2004 31

Example usage use an assertion whenever you would have written a comment that asserts an invariant. For example: if (i % 3 == 0) {... else if (i % 3 == 1) {... else { assert i % 3 == 2 : i;... 10/14/2004 32

Mechanics of Assertion Checking Assertions can be added for some or all of the routines that have documented assertions. Pre-conditions are checked at the start of public and private routines. Post-conditions are checked at the end of public and private routines. Invariants are checked after constructors and at the start and end of public routines. 10/14/2004 33