Design by Contract Ranga Rodrigo based on Mark Priestley's Lectures.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Design by Contract.
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Control Structures Ranga Rodrigo. Control Structures in Brief C++ or JavaEiffel if-elseif-elseif-else-end caseinspect for, while, do-whilefrom-until-loop-end.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Chair of Software Engineering Software Architecture Prof. Dr. Bertrand Meyer Lecture 6: Exception Handling.
1 Design by Contract Building Reliable Software. 2 Software Correctness Correctness is a relative notion  A program is correct with respect to its specification.
Inheritance 2 Ranga Rodrigo Based on Mark Priestley's Lectures.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Chair of Software Engineering ATOT - Lecture 25, 30 June Advanced Topics in Object Technology Bertrand Meyer.
Chair of Software Engineering OOSC - Summer Semester Object-Oriented Software Construction Bertrand Meyer Lecture 15: Exception handling.
-5- Exception handling What is an exception? “An abnormal event” Not a very precise definition Informally: something that you don’t want to happen.
Software Testing and Quality Assurance
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
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.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Computer Science 340 Software Design & Testing Design By Contract.
Exceptions COMPSCI 105 S Principles of Computer Science.
Ranga Rodrigo. Class is central to object oriented programming.
PRAGMATIC PARANOIA Steven Hadfield & Anthony Rice.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Object Oriented Programming
Program Errors Syntax errors Logic errors
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
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/
More About Classes Ranga Rodrigo. Information hiding. Copying objects.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
More About Classes Ranga Rodrigo. Quiz: Question 1 Write the following C++ code in Eiffel. void covert { int i ; float f(1.41) ; i = (int) f ; }
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Exception Handling How to handle the runtime errors.
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.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
1 ָ נן oop uException-Handling Mechanism – similar to C++ l throw e signals the occurrence of an exception lThe statement try/catch allows the calling.
Design by Contract Jim Fawcett CSE784 – Software Studio
Design by Contract Jim Fawcett CSE784 – Software Studio
Chapter 10 – Exception Handling
Java Programming Language
Fundamental Error Handling
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Computer Science 340 Software Design & Testing
Java Basics Exception Handling.
CMSC 202 Exceptions.
Exception Handling.
Design by Contract – Exceptions
Presentation transcript:

Design by Contract Ranga Rodrigo based on Mark Priestley's Lectures

Quiz: Question 1 State whether the following statements are true or false. (a)Subclasses can safely strengthen invariants. (b)Weakened preconditions in a subclass are implied by the preconditions in the superclass. (c)Trying to write a stronger precondition has no effect. (d)Strengthened preconditions in a subclass imply the postconditions in the superclass. (e)An attempt to write a weaker postcondition in a subclass has no effect.

Quiz: Soulution 1 State whether the following statements are true or false. (a)Subclasses can safely strengthen invariants. (b)Weakened preconditions in a subclass are implied by the preconditions in the superclass. (c)Trying to write a stronger precondition has no effect. (d)Strengthened preconditions in a subclass imply the postconditions in the superclass. (e)An attempt to write a weaker postcondition in a subclass has no effect. True False True 2 marks

Contract A contract is a mechanism which specifies exactly how an interaction---between people, organizations etc---will take place. The purpose of a contract is so that each party knows exactly what they must do, and what they can expect from the other party.

Contract For example, a contract of employment specifies:  the hours an employee must work, the duties to be carried out, the applicable codes of conduct etc. i.e., the employee's responsibilities;  the salary paid to the employee, holiday allowance, pension arrangements etc. i.e., the employer's responsibilities.

Design by Contract A software design technique introduced by Bertrand Meyer (the primary developer of Eiffel). It applies to the specification of software modules (classes, methods): the idea is that the specification should be viewed as a contract between the supplier and the client of the module. The supplier has the responsibility to provide certain services (in the module) The client has the responsibility to use the module in certain ways This can be viewed as a compile-time relationship between the people writing the code, or a run-time relationship between calling and called routines.

Design by Contract The supplier has the responsibility to provide certain services (in the module). The client has the responsibility to use the module in certain ways. This can be viewed as a compile-time relationship between the people writing the code, or a run-time relationship between calling and called routines.

Contract of a Routine For example, in the case of a routine the supplier provides parameters when calling the routine, which then carries out some operations and possibly returns a value. The obligations on the client (caller) can be expressed as preconditions: they define what must be true before the routine starts. The obligations on the supplier can be expressed as postconditions: they define what must be true after the routine completes.

The contract is therefore: If the client calls the routine in a situation where the preconditions are true, the supplier guarantees to complete the routine in such a way that the postconditions are true.

Interaction with Other Features The DBC mechanism interacts in various ways with other language features: 1.Preconditions should be visible to the client, so that clients can write code which ensures that the preconditions are true before a routine is called. This means that preconditions cannot contain references to "private" features of the class.

Interaction with Other Features The same argument does not apply to postconditions: client code would not normally check that a postcondition had been satisfied, so postconditions can contain "private" data. (The contract view in EiffelStudio displays "private" postconditions, but not the private features they refer to, which is a bit peculiar.) In subclasses, contracts can be redefined by weakening preconditions and strengthening postconditions. Notice that a class invariant is not really part of a class's external contract.

Defensive Programming Defensive programming is the idea that a module should anticipate everything that could go wrong and include code to handle exceptional situations. A divide routine coded defensively might look like this:

safe_divide( top : DOUBLE ; bottom : DOUBLE ) : DOUBLE is do if bottom = 0 then -- do some error handling end Result := top / bottom end DBC discourages this approach, which on the face of it seems a bit odd given the emphasis placed on secure programming.

The arguments in favour of the DBC view:  Unlike defensive programming, the use of a precondition makes the client's responsibilities explicit.  The supplier shouldn't have to compensate for deficiencies in the client: the whole idea of a contract is that if the precondition is not met, it's the client's fault.  In many cases, there is no sensible error handling code that can be written in a routine when its precondition is false. All that can be done is to raise a run-time exception, and this can more simply be done by an assertion checker built in to the run-time system. This means that the design of an exception handling mechanism is closely related to the implementation of DBC.

Exceptions in Java and C++ Java and C++ have very similar exception mechanisms. Here is a simple Java program that generates a run-time exception when an attempt is made to divide by zero. (Exceptions are normally said to be raised or thrown.)

public class Zerodiv { public static void main(String args[]) { int x = 5 ; int y = 0 ; System.out.println("Quotient = " + quotient(x,y)) ; } static int quotient(int x, int y) { return x/y ; }

Exception in thread "main" java.lang.ArithmeticException: / by zero at Zerodiv.quotient(Zerodiv.java:12) at Zerodiv.main(Zerodiv.java:7) The output from this program is the following:

An Exception The exception is a combination of two things: 1.A run-time signal which is passed up the call stack, interrupting the normal flow of control of the program. 2.An object, of class java.lang.ArithmeticException, defining the type of the exception, and possibly containing some data relating to the failure.

static int quotient(int x, int y) { try { return x/y ; } catch (Exception e) { return 0 ; } Exceptions can be caught, or handled, by enclosing the relevant code in a try block:

Catch Statement The catch statement prevents an exception being passed up the call stack, and allows the programmer to provide alternative code to be executed in the exceptional case. An exception will be caught if its type conforms to the type specified in the catch clause.

Try Statement Any statement can be enclosed in a try block, so the exception here could equally well be caught in the main function as follows. Notice that this code specifies the type of the exception more carefully, and provides error handling code that is more appropriate to the situation.

public static void main(String args[]) { int x = 5 ; int y = 0 ; try { System.out.println("Quotient = " + quotient(x,y)) ; } catch (ArithmeticException e) { System.out.println("Can't divide by zero") ; }

C++ and Java Mechanisms There are various refinements and complications which are being ignored here, but the main features of the C++/ Java mechanism are illustrated, namely: 1.Exceptions are modelled as objects, of library or user-defined types. 2.Any statement can be included in a try block, and exceptions caught and handled at that point.

C++ and Java Mechanisms This is therefore a very general mechanism for transferring control and data between arbitrary points in a program, which is being applied to the specific problem of handling exceptions. It raises the possibility of misusing the mechanism to achieve arbitrary transfers (a bit like the famous goto statement), to the detriment of good program structure.

Exceptions in Eiffel Eiffel, by contrast, defines a more restricted notion of exception handling, which is meant to capture only those aspects which are crucial to the problem, and it expresses this syntactically. It is therefore aiming to be more restrictive than C++ and Java, but to provide a simple mechanism which is more secure, in being less open to misuse for other purposes.

Exceptions in Eiffel In Eiffel, exceptions are related to the idea of design by contract. A routine call is said to succeed if it terminates in a state which satisfies its contract, and to fail otherwise. An exception is an event which causes a routine to fail, such as the following:

1.Trying to call a feature on Void. 2.Trying to assign Void to an expanded target. 3.An abnormal condition being detected by the hardware or operating system. 4.Calling a routine that fails (i.e., exceptions are passed up the call stack, as in Java and C++). 5.An assertion not being satisfied, if the appropriate check is being performed at run-time. 6.Executing an explicit instruction to trigger an exception.

Legitimate Responses in Eiffel Java and C++ essentially allow a program to respond in any way to an exception. By contrast, Eiffel recognizes only two legitimate responses:  To retry the routine, presumably after making some attempt to ensure that the exception will not occur again.  To fail: restore the environment to a stable and legal state, and report failure to the calling routine.

The Eiffel syntax for exceptions reflects this, and is very simple: a routine can have a rescue clause containing code which is executed if an exception occurs in the body of the routine, and the rescue can contain a retry statement, which causes the body of the routine to be executed again from the beginning

A rescue clause that does not include a retry statement causes the exception to be passed up the call stack. This means that a routine is forced to satisfy its contract or to fail: you are not meant simply to patch things up in the rescue clause before carrying on. This principle is meant to ensure that if a routine finishes without an exception, the caller can assume that it has met its contract (i.e., its postconditions are true).

quotient(x : INTEGER ; y : INTEGER) : REAL is local division_tried : BOOLEAN do if not division_tried then Result := x / y end rescue division_tried := True retry end As a result of these rules, it is difficult to write Eiffel routines which do arbitrary things like return zero when a division by zero is attempted:

This returns zero if y is zero, because of the automatic initialization of Result when the routine is retried. However, from the DBC point of view, this is a strength, not a weakness. The argument is that if an attempt is made to divide by zero, there is mathematically no correct answer that can be returned. If the routine was equipped with pre and post conditions:

quotient(x : INTEGER ; y : INTEGER) : REAL is require NonZeroDenominator: y /= 0 do Result := x / y ensure IgnoreRoundingErrors: x = Result * y end an exception will automatically be raised if a zero denominator is detected. There is no value that could be returned that would make the postcondition true in all cases, and therefore no way that the routine can meet its contract in this case. There is no alternative but to return an exception.