Design by Contract in Java Concept and Comparison.

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

272: Software Engineering Fall 2008 Instructor: Tevfik Bultan Lecture 2: Design by Contract.
Design by Contract.
Copyright W. Howden1 Programming by Contract CSE 111 6/4/2014.
Design By Contract Using JMSAssert.
Building Bug-Free O-O Software: An Introduction to Design By Contract A presentation about Design By Contract and the Eiffel software development tool.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2013 Lecture 5 Disclaimer. These notes are derived from notes originally.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 8.
272: Software Engineering Fall 2012
Addressing the Challenges of Current Software. Questions to Address Why? What? Where? How?
The Substitution Principle SWE 332 – Fall Liskov Substitution Principle In any client code, if subtype object is substituted for supertype object,
Building bug-free O-O software: An introduction to Design by Contract Eiffel Software Presented by Bert Bruce.
1 Design by Contract Building Reliable Software. 2 Software Correctness Correctness is a relative notion  A program is correct with respect to its specification.
Dept. of Computer Science A Runtime Assertion Checker for the Java Modeling Language (JML) Yoonsik Cheon and Gary T. Leavens SERP 2002, June 24-27, 2002.
Design by Contract ™. 2 Design by Contract A discipline of analysis, design, implementation, management.
Feb 2003 R McFadyen1 Contracts (Ch 13) Used to help understand requirements more completely based on assertions; assertions are applicable to any.
Object Oriented Design An object combines data and operations on that data (object is an instance of class) data: class variables operations: methods Three.
Jan 2005 Ron McFadyen1 Contracts Used to help understand requirements more completely (and so may not always be necessary) based on assertions;
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
1 Specifying Object Interfaces. 2 Major tasks in this stage: --are there any missing attributes or operations? --how can we reduce coupling, make interface.
Software Testing and Quality Assurance
Static and Dynamic Contract Verifiers For Java Hongming Liu.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Lecture 4: The Interface of a Class.
OOP #10: Correctness Fritz Henglein. Wrap-up: Types A type is a collection of objects with common behavior (operations and properties). (Abstract) types.
Karlstad University Computer Science Design Contracts and Error Management Design Contracts and Errors A Software Development Strategy (anpassad för PUMA)
Chair of Software Engineering Concurrent Object-Oriented Programming Prof. Dr. Bertrand Meyer Lecture 9: Contracts and Inheritance (based on work with.
Design by Contract David Talby. Software Correctness When is a class correct? – It ’ s a relative concept; what is required? – But it ’ s the correct.
Eiffel Language and Design by Contract Contract –An agreement between the client and the supplier Characteristics –Expects some benefits and is prepared.
1 © Wolfgang Pelz Design by Contract Design by Contract™ Based on material drawn from: Bertrand.
Design by Contract Advanced Software Tools Seminar Alexander Freidin 2006 Defining Contracts on Method Call Sequences.
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.
Component-Based Software Engineering Components and Interfaces Paul Krause.
Ranga Rodrigo. Class is central to object oriented programming.
Software Engineering Prof. Dr. Bertrand Meyer March 2007 – June 2007 Chair of Software Engineering Static program checking and verification Slides: Based.
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.
Tammy Dahlgren with Tom Epperly, Scott Kohn, and Gary Kumfert Center for Applied Scientific Computing Common Component Architecture Working Group October.
SWE 619 © Paul Ammann Procedural Abstraction and Design by Contract Paul Ammann Information & Software Engineering SWE 619 Software Construction cs.gmu.edu/~pammann/
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
More About Classes Ranga Rodrigo. Information hiding. Copying objects.
OOSCCh11r1:DbC RJL Slide #1 OOSC: Ch11 vs. Predecessors [Meyer:] Equipped with the basic concepts of class, object and genericity, you can by now.
OOSC - JMSAssert. Design By Contract A powerful technique for writing reliable software. Specifying the software purpose with the implementation. Key.
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.
Spec# Andreas Vida. Motivation Correct and maintainable software Correct and maintainable software Cost effective software production Cost effective software.
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.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
1 Assertions. 2 A boolean expression or predicate that evaluates to true or false in every state In a program they express constraints on the state that.
Defensive Programming CNS 3370 Copyright 2003, Fresh Sources, Inc.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
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.
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.
Interfaces CMSC 202. Public Interfaces Objects define their interaction with the outside world through the their public interface. A class' public interface.
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 6 CS 3370 – C++ Functions.
Design by Contract Jim Fawcett CSE784 – Software Studio
Design by Contract Jim Fawcett CSE784 – Software Studio
Used to help understand requirements more completely
Java Modeling Language (JML)
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Computer Science 340 Software Design & Testing
Contract-Based Programming with/without Ada 2012
Presentation transcript:

Design by Contract in Java Concept and Comparison

What is DBC?  Classes of a system communicate with one another on the basis of precisely defined benefits and obligations. [Bertrand Meyer, CACM, Vol. 36, No 9, 1992]

What is DBC? (cont.)  Preconditions of methods A boolean expression which is assumed true when the method gets called  Postconditions of methods A boolean expression which the caller can assume to be true when the method returns  Class invariants consistency conditions of objects must hold for all instances

Preconditions, Postconditions and Class Invariants /** gpa >= 0 */ class Student { protected _gpa; /** * GPA always >=0 gpa >= 0 */ void setGPA (double gpa){…} /** * GPA always >=0 return >= 0 */ double getGPA(){…} }

put (x: ELEMENT; key: STRING) is -- Insert x so that it will be retrievable through key. require count <= capacity not key.empty do... Some insertion algorithm... ensure has (x) item (key) = x count = old count + 1 end Preconditions, Postconditions and Class Invariants (cont.) e.g., inserting a certain element into a dictionary (a table where each element is identified by a certain character string used as key) of bounded capacity.

The Notion of Contract  Obligations (Must ensure precondition) Make sure table is not full and key is a non- empty string. (Must ensure postcondition) Record given element in table, associated with given key.  Benefits (May benefit from postcondition) Get updated table where the given element now appears, associated with the given key. (May assume precondition) No need to do anything if table is full, or key is empty string. Client Supplier

The Notion of Contract (cont.)  Obligations  Satisfy preconditions  Satisfy postconditions  Benefits  No need to check output values  Result guaranteed to comply to postcondition  No need to check input values  Input guaranteed to comply to precondition Client Supplier

Benefits of Design by Contract  Better understanding of software construction  Systematic approach to building bug-free oo systems  Effective framework for debugging, testing and quality assurance  Method for documenting software components  Better control of the inheritance mechanism  Technique for dealing with abnormal cases, effective exception handling

Current Existing Tools  Formal documentation informal, implicit vs. formal, explicit  Runtime validation translate the contract into runtime assertions most common  Static analysis use model checking, theorem prover to analyze at compile time

Current Existing Tools (cont.)  JDK1.4: assert  Eiffel  iContract by Reto Kramer, Cambridge Technology Partners  JASS  JMSAssert by man machine systems  Jtest and Jcontract by parasoft

What are These Tools For?  Most are runtime validation and formal documentation  programmer-provided assertions into source code, using a preprocessor  At runtime, check if these assertions are violated—possibly, throw exceptions

What are These Tools For? (cont.)  Requirement: programmer needs to write assertions (preconditions, postconditions, class invariants) in certain documentation format.  Run the preprocessors (possibly with options) to get the instrumented program.  Result: avoidance of any runtime exceptions due to violation of assertions (but still throw other exceptions).

Comparison Between These Tools Expressive ness UsabilityRuntime Check Static Analysis JDK1.4 Low, not specific Low level feature YesNo iContract Specified contract Tool with multiple features YesNo My Tool Specified contract Tool with multiple features YesHas interface to integrate with static error checker

Comparison Between These Tools (cont.)  How expressiveness?  How to deal with class hierarchies?  Other design issues  Implementation issues  Additional features

How Expressivness?  JDK1.4: low level features. dose not specify precondition, postconditon and invariant  Other tools: ---preconditions, postconditions and invariants to be checked at different entry of the program ---some have quantifiers: forall, exists, implies ---value at entry level of a method vs. value at return level of a method

How Expressiveness? (cont.)  Forall (iContract): forall in |  Exists (iContract): exists in |  implies (iContract): C implies I e.g., each employee must be on the employment-list of all it’s employees_ != null implies forall Emplyee e in employees_.elements() | exists Employer c in e.getEmployers() | c == this

How Expressiveness? (cont.)  Old + 1  Old value, $prev a == $prev(a) + val

Class Hierarchies (Class extension, interface implementation, interface extension and innerclasses)  Why? type, syntax vs. semantic more strict on what a subtype should do  Example interface human{ object getFood(); } class cat implements human{ // might return raw rat, if no contract is made here public object getFood() {…} }

Class Hierarchies (cont.)  JDK1.4: No.  Eiffel: --OR in precondition, AND in postcondition  iContract, JMSAssert: --invariants: conjuncted (stronger in subtype) --postconditions: conjuncted (stronger in subtype) --preconditions: disjuncted (weaker in subtype)  JASS: --must implement the interface jass.runtime.refinement

Class Hierarchies (cont.)  Examples (JMSAssert) interface Employee { /** return > 25 */ int getAge(); /** age > 25 */ void setAge( int age); } class ImpEmployee implements Employee { protected int eage; /** return < 65 */ public int getAge(){ return age_; } /** age < 65 */ public void setAge( int age) { eage = age; } … } Subclass can choose to deal with more conditions, but must offer at least the same service.

Other Design Issues  How to avoid non-terminating recursion? --iContract: keeps track of the call-chain at runtime to prevent recursive non-termination checks. --JASS: assertion is not checked at the first level of internal calls. Beyond that, no restriction. --JMSAssert: no specified.

Other Design Issues (cont.)  Example of recursive calls: 1: /**Example that demonstrates the automatic avoidance of 2: * recursive, non-terminating invariant checks 3: * 4: forall Employee employee 5: * in this.getEmployees().elements() | 6: * employee.getEmployer() == this 7: */ 8: class Employer { 9: 10: public static void main(String arv[]) { 11: Employer company = new Employer(); 12: Employee george = new Employee(); 13: company.add( george ); 14: }

Other Design Issues (cont.)  Example of recursive calls (cont.): 15: 16: protected Vector employees_ = new Vector(); 17: 18: Enumeration getEmployees() { 19: return employees_.elements(); 20: } 21: 22: void add(Employee employee) { 23: employee.setEmployer( this ); 24: employees_.addElement( employee ); 25: } 26: } 27:...

Other Design Issues (cont.)  Solution to prevent non-terminating recursive calls (iContract) /** age_ > 0 */ public class Employee implements Person { //#*# private java.util.Hashtable __icl_ = new java.util.Hashtable(); private synchronized void __inv_check_at_entry__Employee(

Other Design Issues (cont.)  Solution to prevent non-terminating recursive calls (iContract), cont. Thread thread, String loc) { if ( !__icl_.containsKey(thread) ) { // recursion depth 0 __icl_.put(thread, new Integer(1)); __check_invariant____Employee(loc); // evaluates the invariant } else // inc recursion depth __icl_.put(thread, new Integer( ((Integer)__icl_.get(thread)).intValue()+1)); } //#*#

Implementation Issues  Performance tuning compile options to specify how strict the assertion check is. e.g., iContract: java iContract.Tool –mpre,post,inv C.java > C_instr.java

Additional Features  iContract: Binary contract repositories: compiled contract to be included in the distribution.  Jtest and Jcontract: Test tool implementing design by contract.

Main Features of My Tool  Formal documentation  @invariant, forall, exists, implies, x’  Compatible with Java 1.4  Runtime validation  Interface with the static analysis tool

Current Status  Done: --javadoc @invariant, etc. --grammar for blocks of comment that are in certain format, in.jjt form (using JavaCC): a!=0&&b<0  To be done: --incorporate the grammar for comment into the AST of the whole program. --instrumentation of the assertions