Contracts. Dr. C. Constantinides. June 5, Department of Computer Science and Software Engineering Concordia University Montreal, Canada 1/71
|
|
- Magdalen Booker
- 5 years ago
- Views:
Transcription
1 Contracts Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada June 5, /71
2 Contracts in human affairs In human affairs we form legally binding documents specifying an agreement between parties, where each party is expected to satisfy certain obligations and is entitled to expect certain benefits. The legality factor implies that if one of the parties does not hold up to his or her obligations, one (perhaps a third party) should be able to assign blame. 2/71
3 Booking a theater seat: An analogy example Assume that you wish to book a seat for a theater play and you contact the theater s booking office in order to purchase a ticket. The ticket that you purchase constitutes a legally binding document between the theater booking office ( office ) that supplies a service and you ( the client ) who are purchasing the service. 3/71
4 Booking a theater seat: Obligations of the client There are certain obligations that you have as a client before this service can be provided. First, you must make a full payment. You must appear at the theater on time. You must also present a valid ticket, together with any other supporting documentation. For example, if you are a minor or if you are a student and you are eligible for a reduced price, you must also supply valid identification. Furthermore, you may also be required to follow some dress code. 4/71
5 Booking a theater seat: Obligations of the client /cont. Note that it is not the responsibility of the office to do any of these for you. For example, if you do not show up on time or if you do not have a valid ticket and identification, you will not be allowed in. 5/71
6 Booking a theater seat: Obligations of the client /cont. In formal logic, your obligations can be captured by a logical expression that must hold before you may enter the auditorium, i.e. before the service is provided. We refer to this expression as a precondition. The office benefits from your obligations: First, it collects a payment and second, it does not need to worry about you being on-time. Thus, the precondition constitutes the obligation of the client but also the benefit of the supplier. 6/71
7 Booking a theater seat: Obligations of the supplier On the other hand, the office has certain obligations of its own: The play to be shown must be the one advertised (the one which you have purchased the ticket for), and the play must start on-time. Furthermore, the rooms (auditorium, reception, bar, etc.) of the building must be well maintained (air-conditioned, heated). You may see the obligations of the office as your benefits. 7/71
8 Booking a theater seat: Obligations of the supplier In formal logic, the office s obligations can be captured by a logical expression that must hold once the play has finished (i.e. by the successful termination of the service). We refer to this expression as a postcondition. Thus the postcondition constitutes the obligation of the supplier but also the benefit of the client. 8/71
9 Booking a theater seat: Obligations and benefits in terms of formalisms We can tabulate the above discussion illustrating how clients and suppliers relate to preconditions and postconditions of a given service. Obligations Benefits Client Precondition Postcondition Supplier Postcondition Precondition 9/71
10 Booking a theater seat: Obligations and benefits /cont. It is important to note that a party that acts as a supplier for a given service, may also act as a client for another service that is needed to perform its obligations as a supplier. For example, the theater would normally act as a client to a number of suppliers in the city, such as vendors, catering services, security services, etc. 10/71
11 Booking a theater seat: General obligations There are also certain general obligations that must always be met such that the building must meet safety standards,that you cannot vandalize the rooms or assault the staff or other clients, etc. If any of these general obligations are violated, then the agreement between you and the office is also violated. In formal logic, these general obligations are captured by a logical expression called the invariant. The invariant must always hold from the moment you purchase the service until the moment the service has been successfully completed. 11/71
12 Contract programming In programming we adopt the metaphor of contracts for collaborating software elements. The agreement involved is an operation to be performed by a software element such as a method. The method acts as a supplier to any client wishing to make use of its services. The method of design by contract (dbc) (or contract programming) recommends that every software element should be associated with a contract as a specification of its interaction with the rest of the world. Note that nothing prevents a software element from acting as both a supplier and a client with different elements. 12/71
13 Contract programming /cont. Even though contract programming is not confined to object-oriented programming (OOP), we will use OOP as our underlying programming paradigm. In OOP we can build contracts by associating each method (which forms part of the interface of the class) with a set of preconditions and a set of postconditions, and by associating an invariant with the class. 13/71
14 Defining assertions on methods A contract for a software element is specified by assertions: preconditions and postconditions. Precondition: Logical expression describing the state of the system before the execution of an operation. Postcondition: Logical expression describing the state of the system after the execution and successful termination of an operation. 14/71
15 Defining assertions on classes Since a contract specifies the relation between an element with the outside world, we should then specify assertions for all public (and protected) methods, i.e. those which form part of the interface of the class. 15/71
16 Defining a class invariant In OOP we can associate each class with an invariant. The class invariant specifies the valid states for every instance of the class. An instance of a class which does not uphold the invariant is not a valid instance. 16/71
17 Contract programming with adbc Developed by the Ansymo research group at the University of Antwerp, Belgium, adbc is a small library that adds support for contract programming to the AspectJ programming language and subsequently to Java as well as AspectJ is a superset of Java. In adbc contracts are specified as Javascript expressions within Java annotations. Methods and advice can have pre-and postconditions; classes and aspects can have invariants. 17/71
18 Contract programming with adbc The following keywords are specifies the specifies the $this refers to the current object. $result refers to the return value of a method/advice, available in postconditions. $old(expr) refers to the old function evaluates an expression before the method/advice is executed, stores the result, such that it is available in postconditions. 18/71
19 A bounded stack Consider a bounded stack that holds string objects. The Stack Abstract Data Type (ADT) implements a last-in-first-out protocol. public class Stack { public ArrayList <String> collection; public int capacity; public int top = -1; Stack (int capacity) { this.capacity = capacity; this.collection = new ArrayList<String>(capacity); } public void push (String str) {...} public String pop () {...} public String top () {...} public boolean isfull () {...} public boolean isempty () {...} public int getsize () {...} public int getcapacity() {...} } 19/71
20 Defining a class contract In OOP we can associate each class with an invariant. The class invariant specifies the valid states for every instance of the class. An instance of a class which does not uphold the invariant is not a valid instance. In this example the class invariant should state that the size of the stack should never be negative; that the capacity of the stack can only be a positive integer, and finally that the size cannot exceed the ({ "$this.top >= -1", "$this.capacity > 0", "$this.top <= $this.capacity" }) 20/71
21 Defining method contracts A contract for a software element is specified by assertions: preconditions and postconditions. Since a contract specifies the relation between an element with the outside world, we should then specify assertions for all public (and protected) methods, i.e. those which form part of the interface of the class. 21/71
22 Defining method contracts /cont. Class Stack contains methods void push(string) that places an element onto the collection, String pop() that removes and returns the topmost element from the collection and String top() that returns but does not remove the topmost element of the collection. 22/71
23 Defining method contracts /cont. For the constructor Stack (int capacity), the postcondition states that the collection atrtribute is not ({"$this.collection!= null" }) Stack (int capacity) { this.capacity = capacity; this.collection = new ArrayList<String>(capacity); } 23/71
24 Defining method contracts /cont. For method void push (..), the first precondition states that the element passed to the method must be a valid string. The second precondition states that an element can only be placed on a non-full ({ "str!= null", "$this.isfull() == false" }) public void push (String str) { collection.add(++top, str); } 24/71
25 Defining method contracts /cont. The postcondition states that the element is now held in the collection, that the element was placed on the top (and thus it is retrievable according to the stack protocol), and that the current size of the collection should now be one greater than the size of the collection prior to invoking the ({ "$this.collection.contains(str)", "$this.collection.get($this.top) == str", "$this.getsize() == $old($this.getsize()) + 1" }) public void push (String str) { collection.add(++top, str); } 25/71
26 Defining method contracts /cont. For method String pop (), the precondition states that the collection must not be ({ "$this.isempty() == false" }) public String pop () { String element = collection.get(top--); return element; } 26/71
27 Defining method contracts /cont. The postcondition states that the element retrieved is of valid type, that the element retrieved is the one previously held on top of the stack, and that the size of the collection is one less that the size of the collection prior to invoking the ({ "$result!= null", "$result == $old($this.top())", "$this.getsize() == $old($this.getsize()) - 1" }) public String pop () { String element = collection.get(top--); return element; } 27/71
28 Defining method contracts /cont. For method String top (), the precondition states that the collection must not be ({ "$this.isempty() == false" }) public String top () { String result = collection.get(top); return result; } 28/71
29 Defining method contracts /cont. The postcondition states that the element retrieved is not null, that the element retrieved is the one previously held on the top of the stack, and that the size of the collection has not ({ "$result!= null", "$result == $old($this.top())", "$this.getsize() == $old($this.getsize())" }) public String top () { String result = collection.get(top); return result; } 29/71
30 Defining method contracts /cont. For method int getsize (), there is no precondition. The postcondition states that the resulting value should be a non-negative ({ "true" ({ "$result >= 0" }) public int getsize () { return this.top + 1; } 30/71
31 Defining method contracts /cont. Finally for method int getcapacity(), there is no precondition. The postcondition states that the resulting value should be ({ "true" ({ "$result > 0" }) public int getcapacity() { return this.capacity; } 31/71
32 Simulating failure scenarios We will simulate a number scenarios, imposing failures on preconditions, postconditions and invariants. For each scenario, we will state a) why the program failed and b) where exactly the program failed and c) who is to blame for the failure. 32/71
33 Invariant failure Consider the test program below: Stack stack = new Stack(0); stack.push("all"); stack.push("your"); stack.push("base"); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); This results in invariant failure as the client attempted to instantiate a stack of zero capacity: Exception in thread "main" [...]: Invariant broken! (postcondition) Contract: $this.capacity > 0 Where: Stack Blame: (method not found) 33/71
34 Invariant failure and class constructor The invariant failed because upon termination of the constructor, attribute capacity is not positive. Recall that we have not placed an appropriate precondition in the class constructor. As a result, the failure came from the invariant upon termination of the constructor method. Let us now add a precondition to the constructor, stating that the capacity parameter must be a positive ({"capacity > 0"}) Stack (int capacity) {...} Note the difference between $this.capacity in the invariant contract which denotes an attribute, and capacity in the constructor contract which denotes a parameter. 34/71
35 Invariant failure and class constructor /cont. If we now attempted to create an object with zero capacity Stack stack = new Stack(0); we would get the following constructor precondition failure: Exception in thread "main" [...] PreConditionException: Precondition broken! Contract: capacity > 0 Where: Stack(int) Blame: Test.main 35/71
36 Precondition failures ex. 1 Consider the test program below: Stack stack = new Stack(2); stack.push("all"); stack.push("your"); stack.push("base"); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); This results in precondition failure at the third call to push() as this exceeds the capacity of the stack: Exception in thread "main" [...]: Precondition broken! Contract: $this.isfull() == false Where: public void Stack.push(java.lang.String) Blame: Test.main 36/71
37 Precondition failures ex. 2 Consider the test program below: Stack stack = new Stack(3); stack.push("all"); stack.push("your"); stack.push("base"); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); This results in precondition failure at the last call to pop() as the stack has already become empty: Exception in thread "main" [...]: Precondition broken! Contract: $this.isempty() == false Where: public java.lang.string Stack.pop() Blame: Test.main 37/71
38 Postcondition failures To simulate postcondition failures we will inject errors into the implementation of the methods of the Stack class. We will subsequently expect that the tool will indicate the appropriate failure type and pick up the particular assertion that failed. 38/71
39 Postcondition failures: Faulty pop() Consider the (faulty) implementation of method pop() that fails to decrement variable top upon ({ "$this.isempty() == false" ({ "$result!= null", "$result == $old($this.top())", "$this.getsize() == $old($this.getsize()) - 1" }) public String pop () { String element = collection.get(top); return element; } 39/71
40 Postcondition failures: Faulty pop() /cont. Consider the test program below: Stack stack = new Stack(3); stack.push("all"); stack.push("your"); stack.push("base"); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); The program responds with Exception in thread "main" [...]: Postcondition broken! Contract: $this.getsize() == $old4-1 Where: public java.lang.string Stack.pop() Blame: Stack.public java.lang.string Stack.pop() 40/71
41 Postcondition failures: Faulty top() Consider the (faulty) implementation of method top() that decrements variable top upon inspection, thus changing the size of the stack, whereas in fact it should ({ "$this.isempty() == false" ({ "$result!= null", "$this.getsize() == $old($this.getsize())" }) public String top () { String result = collection.get(top--); return result; } 41/71
42 Postcondition failures: Faulty top() /cont. Consider the test program below: Stack stack = new Stack(3); stack.push("all"); stack.push("your"); stack.push("base"); System.out.println(stack.top()); System.out.println(stack.pop()); System.out.println(stack.pop()); The program responds with Exception in thread "main" [...]: Postcondition broken! Contract: $this.getsize() == $old2 Where: public java.lang.string Stack.top() Blame: Stack.public java.lang.string Stack.top() 42/71
43 Two cautionary test cases: Faulty top() The test program is as follows: Stack stack = new Stack(3); stack.push("all"); stack.push("your"); stack.push("base"); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); The program responds with Exception in thread "main" [...]: Postcondition broken! Contract: $result == $old3 Where: public java.lang.string Stack.pop() Blame: Stack.public java.lang.string Stack.pop() 43/71
44 Two cautionary test cases: Faulty top() /cont. The error message is not straightforward. Method pop() seems to fail to meet its postcondition even though its implementation is correct. The error lies in the conflict between the correct implementation of method pop() and a faulty method that is part of its specification, namely top(). When making the call to pop(), adbc assumes that the method s specifications is correct. As a result, adbc (mistakenly) concludes that the error can only be originating from the implementation of pop(). 44/71
45 Two cautionary test cases: Faulty getsize() Consider the (faulty) implementation of method getsize() that does not increment the value of variable top, whereas in fact it should, thus allowing top to have a negative ({ "true" ({ "$result >= 0" }) public int getsize () { return this.top; } 45/71
46 Two cautionary test cases: Faulty getsize() /cont. The test program is as follows: Stack stack = new Stack(3); stack.push("all"); stack.push("your"); stack.push("base"); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); The program responds with Exception in thread "main" [...]: Precondition broken! Contract: $this.isempty() == false Where: public java.lang.string Stack.pop() Blame: Test.main 46/71
47 Two cautionary test cases: Faulty getsize() /cont. The error message is again not straightforward. Method pop() seems to fail meeting its postcondition even though its implementation is correct. The error lies in the conflict between the correct implementation and a faulty method that is part of the specification, namely getsize(). 47/71
48 How do we avoid the problem? We must carefully consider the order in which we implement and test the methods in a class. For example, the contracts for both methods push() and pop() depend on method getsize(). The contract for method pop() depends on method top(). The contract for method top() depends on method getsize(). Recommendation: Follow a bottom-up approach to implementation and testing, i.e. getsize(), top(), (push(), pop()). 48/71
49 A bounded queue Consider a bounded queue that holds string objects. The Queue ADT implements a first-in-first-out protocol. public class Queue { public ArrayList <String> collection; public int capacity; public Queue(int capacity) { this.collection = new ArrayList<String>(); this.capacity = capacity; } public void enqueue (String str) {...} public String dequeue () {...} public boolean isfull () {...} public boolean isempty () {...} public int getsize () {...} public int getcapacity() {...} } 49/71
50 Defining a class contract The class invariant should state that the size of the queue should never be ({ }) "$this.collection.size() >= 0", "$this.capacity > 0", "$this.collection.size() <= $this.capacity" 50/71
51 Defining a constructor contract For the constructor Queue(), the precondition states that the parameter must be a positive number. The postcondition states that the attribute collection is not null and the attribute capacity is a positive ({"capacity > ({ "$this.collection!= null", "$this.capacity > 0" }) public Queue(int capacity) { this.collection = new ArrayList<String>(); this.capacity = capacity; } 51/71
52 Defining method contracts For method enqueue (String str), the precondition states that the parameter str is not null and that the collection is not already ({ "str!= null", "$this.isfull() == false" }) public void enqueue (String str) { collection.add(str); } 52/71
53 Defining method contracts /cont. The postcondition states that upon successful termination of the method a) the element is now held in the collection and b) the size of the collection has been increased by ({ "str!= null", "$this.isfull() == false" ({ "$this.collection.contains(str)", "$this.getsize() == $old($this.getsize()) + 1" }) public void enqueue (String str) { collection.add(str); } 53/71
54 Defining method contracts /cont. For method dequeue (), the precondition states that the collection must not be ({"$this.isempty() == false"}) public String dequeue () { String element = collection.remove(0); return element; } 54/71
55 Defining method contracts /cont. The postcondition states that upon successful termination of the method a) the element retrieved is not null, b) the element retrieved is the one previously held at the front of the queue, and c) the size of the collection has been decreased by ({"$this.isempty() == ({ "$result!= null", "$result == $old($this.collection.get(0))", "$this.getsize() == $old($this.getsize()) - 1" }) public String dequeue () { String element = collection.remove(0); return element; } 55/71
56 Defining method contracts /cont. For method int getsize (), there is no precondition. The postcondition states that the resulting value should be a non-negative ({"true" ({"$result >= 0" }) public int getsize () { return collection.size(); } 56/71
57 Defining method contracts /cont. For method int getcapacity(), there is no precondition. The postcondition states that the resulting value should be a > 0"}) public int getcapacity() { return this.capacity; } 57/71
58 Simulating failure scenarios: Constructor precondition failure Consider the test program below: Queue queue = new Queue(0);... This results in a constructor precondition failure as the client attempted to create a queue with zero capacity: Exception in thread [...].PreConditionException: Precondition broken! Contract: capacity > 0 Where: public Queue(int) Blame: Test.main 58/71
59 Simulating failure scenarios: Method precondition failure Consider the test program below: Queue queue = new Queue(2); queue.enqueue("all"); queue.enqueue("your"); queue.enqueue("base"); This results in a precondition failure of method enqueue() as the client attempted to insert an element in a full collection: Exception in thread [...].PreConditionException: Precondition broken! Contract: $this.isfull() == false Where: public void Queue.enqueue(java.lang.String) Blame: Test.main 59/71
60 Postcondition failure: Faulty dequeue() Consider the (faulty) implementation of method dequeue() that removes an element from position 1 (instead of from position ({"$this.isempty() == ({ "$result!= null", "$result == $old($this.collection.get(0))", "$this.getsize() == $old($this.getsize()) - 1" }) public String dequeue () { String element = collection.remove(1); return element; } 60/71
61 Postcondition failure: Faulty dequeue() /cont. Consider the test program below: Queue queue = new Queue(5); queue.enqueue("all"); queue.enqueue("your"); queue.enqueue("base"); System.out.println(queue.dequeue()); System.out.println(queue.dequeue()); System.out.println(queue.dequeue()); This results in a postconfition failure: Exception in thread "main" [...].PostConditionException: Postcondition broken! Contract: $result == $old3 Where: public java.lang.string Queue.dequeue() Blame: Queue.public java.lang.string Queue.dequeue() 61/71
62 Inheritance and subtyping Classes (and interfaces) define types. All instances of a given class constitute legitimate values of that type. The inheritance relationship between classes (and between classes and interfaces) creates a related set of types (subtype relationship). Type T 2 is a subtype of type T 1 if every legitimate value of T 2 is also a legitimate value of T 1. We say that T 1 is the supertype of T 2. 62/71
63 Inheritance and subtyping /cont. For example, the relationship between shape and triangle defines a subtype relationship as every triangle is a shape (but not vice versa) and thus the set of shapes is a superset of the set of triangles. The relationship between stack and vector does not define a subtype relationship even though it may be practical to deploy inheritance and define the former in terms of the latter. The type defined by the subclass is a subset of the type defined by its superclasses as the set of all instances of a subclass is included in the set of all instances of its superclass. 63/71
64 Inheritance of contractual specifications in adbc The keyword $super in a subclass refers to the corresponding assertion in the superclass. Consider the following ({"$super"}) public class Queue2 extends Queue ({"$super"}) public Queue2 (int capacity) { super(capacity); } } 64/71
65 Inheritance of contractual specifications in adbc /cont. For the following program statement Queue2 queue = new Queue2(0); we get the following Exception in thread [...]PreConditionException: Precondition broken! Contract: capacity > 0 Where: public Queue(int) Blame: Queue2.<init> 65/71
66 Inheritance of contractual specifications in adbc /cont. $super is optional since by default subclasses inherit the contractual specifications of their superclasses. public class Queue2 extends Queue { public Queue2 (int capacity) { super(capacity); } } 66/71
67 Inheritance of contractual specifications in adbc /cont. $super can be used in logical expressions in order to extend a specification. Let a requirement for Queue2 be that its instances must have a maximum capacity of ({"$super && $this.capacity < 4"}) public class Queue2 extends Queue ({"$super && capacity < ({"$super"}) public Queue2 (int capacity) { super(capacity); } } 67/71
68 The Liskov Substitution Principle The Liskov substitution principle (LSP) states that in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S. This implies that an instance of a subclass can appear wherever an instance of a superclass is expected. For example, instances of class Triangle can appear in any place where an instance of class Shape is expected. 68/71
69 Inheritance, LSP and contracts: Preconditions What happens when a subclass needs to introduce different specifications than the ones in the superclass? There are two important things to recall here: First, a precondition specifies the obligations of the client, and second, instances of a subclass can be provided in all places where an instance of a superclass is expected. With these two points in mind, we can argue that if a precondition in a subclass is stronger than that of the superclass, then this is not fair to the client who has already reached a contractual agreement with the superclass. This implies that a precondition in a subclass can be the same or weaker than that of the superclass. In other words, the subclass may demand less from its clients than what the superclass already demands. 69/71
70 Inheritance, LSP and contracts: Postconditions Recall that a postcondition specifies the obligation of the supplier. With this in mind, we can argue that if a postcondition in a subclass is weaker than that of the superclass, then this is not fair to the client who has already reached a contractual agreement with the superclass. This implies that a postcondition in a subclass can be the same or stronger than that of the superclass. In other words, the subclass may offer more to its clients than what the superclass already offers. 70/71
71 Inheritance, LSP and contracts In conclusion: Preconditions cannot be strengthened in a subtype. Postconditions cannot be weakened in a subtype. As a result, Queue2 violates the Liskov substitution principle. 71/71
Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012
Why Design by Contract What s the difference with Testing? CS 619 Introduction to OO Design and Development Design by Contract Fall 2012 Testing tries to diagnose (and cure) defects after the facts. Design
More informationCSC Advanced Object Oriented Programming, Spring Specification
CSC 520 - Advanced Object Oriented Programming, Spring 2018 Specification Specification A specification is an unambiguous description of the way the components of the software system should be used and
More informationUC Santa Barbara. CS189A - Capstone. Christopher Kruegel Department of Computer Science UC Santa Barbara
CS189A - Capstone Christopher Kruegel Department of Computer Science http://www.cs.ucsb.edu/~chris/ Design by Contract Design by Contract and the language that implements the Design by Contract principles
More informationClasses, subclasses, subtyping
1 CSCE 314: Programming Languages Dr. Flemming Andersen Classes, subclasses, subtyping 2 3 Let me try to explain to you, what to my taste is characteristic for all intelligent thinking. It is, that one
More informationa correct statement? You need to know what the statement is supposed to do.
Using assertions for correctness How can we know that software is correct? It is only correct if it does what it is supposed to do. But how do we know what it is supposed to do? We need a specification.
More informationAdvanced JML Erik Poll Radboud University Nijmegen
JML p.1/23 Advanced JML Erik Poll Radboud University Nijmegen JML p.2/23 Core JML Remember the core JML keywords were requires ensures signals invariant non null pure \old, \forall, \result JML p.3/23
More informationAssertions. Assertions - Example
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,
More informationINHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U
C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes
More informationOO Design Principles
OO Design Principles Software Architecture VO (706.706) Roman Kern Institute for Interactive Systems and Data Science, TU Graz 2018-10-10 Roman Kern (ISDS, TU Graz) OO Design Principles 2018-10-10 1 /
More informationAdding Contracts to C#
Adding Contracts to C# Peter Lagace ABSTRACT Design by contract is a software engineering technique used to promote software reliability. In order to use design by contract the selected programming language
More informationCS 215 Software Design Sample midterm solutions
Software Design Sample midterm solutions 1. The administration at Happy Valley School District is redesigning the software that manages information about its students. It has identified an abstract class
More informationDesign by Contract in Eiffel
Design by Contract in Eiffel 2002/04/15 ctchen@canthink.com.com.tw.tw Reference & Resource Bertrand Meyer, Object-Oriented Oriented Software Construction 2nd,, 1997, PH. Bertrand Meyer, Eiffel: The Language,,
More informationPROCESS DEVELOPMENT METHODOLOGY The development process of an API fits the most fundamental iterative code development
INTRODUCING API DESIGN PRINCIPLES IN CS2 Jaime Niño Computer Science, University of New Orleans New Orleans, LA 70148 504-280-7362 jaime@cs.uno.edu ABSTRACT CS2 provides a great opportunity to teach an
More informationThe Contract Pattern. Design by contract
The Contract Pattern Copyright 1997, Michel de Champlain Permission granted to copy for PLoP 97 Conference. All other rights reserved. Michel de Champlain Department of Computer Science University of Canterbury,
More informationReadability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.
Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute. Abelson & Sussman Use a good set of coding conventions, such as the ones given in the
More informationClasses, interfaces, & documentation. Review of basic building blocks
Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform
More informationType Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004
Type Hierarchy Comp-303 : Programming Techniques Lecture 9 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 9 Comp 303 : Programming Techniques Page 1 Last lecture...
More informationData Structures. BSc in Computer Science University of New York, Tirana. Assoc. Prof. Marenglen Biba 1-1
Data Structures BSc in Computer Science University of New York, Tirana Assoc. Prof. Marenglen Biba 1-1 General info Course : Data Structures (3 credit hours) Instructor : Assoc. Prof. Marenglen Biba Office
More informationObject Oriented Programming: Based on slides from Skrien Chapter 2
Object Oriented Programming: A Review Based on slides from Skrien Chapter 2 Object-Oriented Programming (OOP) Solution expressed as a set of communicating objects An object encapsulates the behavior and
More information3. Design by Contract
3. Design by Contract Oscar Nierstrasz Design by Contract Bertrand Meyer, Touch of Class Learning to Program Well with Objects and Contracts, Springer, 2009. 2 Roadmap > Contracts > Stacks > Design by
More informationFortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)
2014-03-07 Preface Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming) Coordinates: Lecturer: Web: Studies: Requirements: No. 185.211, VU, 3 ECTS Franz Puntigam http://www.complang.tuwien.ac.at/franz/foop.html
More informationMidterm Exam (REGULAR SECTION)
Data Structures (CS 102), Professor Yap Fall 2014 Midterm Exam (REGULAR SECTION) October 28, 2014 Midterm Exam Instructions MY NAME:... MY NYU ID:... MY EMAIL:... Please read carefully: 0. Do all questions.
More informationCSE 331 Midterm Exam 2/13/12
Name There are 10 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes, closed
More informationCsci 102: Sample Exam
Csci 102: Sample Exam Duration: 65 minutes Name: NetID: Student to your left: Student to your right: DO NOT OPEN THIS EXAM UNTIL INSTRUCTED Instructions: Write your full name and your NetID on the front
More informationReferences: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1
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,
More informationCHAPTER 6 Design by Contract. Literature. When Design by Contract? Why Design By Contract?
CHAPTER 6 Design by Contract Literature Introduction When, Why & What Pre & Postconditions + Invariants + Example: Stack Implementation Redundant Checks vs. Assertions Exception Handling Assertions are
More informationQueue Implemented with a CircularArray. Queue Implemented with a CircularArray. Queue Implemented with a CircularArray. Thursday, April 25, 13
Queue Implemented with 1 2 numitems = enqueue (); 1 Queue Implemented with 2 numitems = 2 enqueue (); enqueue (); 2 Queue Implemented with 2 numitems = 2 enqueue (); enqueue (); enqueue (5); enqueue (6);
More informationCSE 331 Final Exam 3/16/15 Sample Solution
Question 1. (12 points, 3 each) A short design exercise. Suppose Java did not include a Set class in the standard library and we need to store a set of Strings for an application. We know that the maximum
More informationCS 10, Fall 2015, Professor Prasad Jayanti
Problem Solving and Data Structures CS 10, Fall 2015, Professor Prasad Jayanti Midterm Practice Problems We will have a review session on Monday, when I will solve as many of these problems as possible.
More informationInterfaces & Generics
Interfaces & Generics CSC207 Winter 2018 The Programming Interface The "user" for almost all code is a programmer. That user wants to know:... what kinds of object your class represents... what actions
More informationObject-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1
Object-Oriented Languages and Object-Oriented Design Ghezzi&Jazayeri: OO Languages 1 What is an OO language? In Ada and Modula 2 one can define objects encapsulate a data structure and relevant operations
More informationType Hierarchy. Lecture 6: OOP, autumn 2003
Type Hierarchy Lecture 6: OOP, autumn 2003 The idea Many types have common behavior => type families share common behavior organized into a hierarchy Most common on the top - supertypes Most specific at
More informationcsci 210: Data Structures Stacks and Queues
csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks
More informationCS3500: Object-Oriented Design Fall 2013
CS3500: Object-Oriented Design Fall 2013 Class 3 9.13.2013 Plan for Today Web-CAT Announcements Review terminology from last class Finish Recipe implementation of StackInt as a class Abstraction Barrier
More information17. 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 Outline Introduction (BIT, assertion, executable assertion, why?) Implementation-based vs responsability-based assertions Implementation
More informationCMP Points Total Midterm Spring Version (16 Points) Multiple Choice:
Version 1 Instructions Write your name and version number on the top of the yellow paper. Answer all questions on the yellow paper. One question per page. Use only one side of the yellow paper. 1. (16
More information[ L5P1] Object-Oriented Programming: Advanced Concepts
[ L5P1] Object-Oriented Programming: Advanced Concepts Polymorphism Polymorphism is an important and useful concept in the object-oriented paradigm. Take the example of writing a payroll application for
More informationComputer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)
Computer Science 62 Bruce/Mawhorter Fall 16 Midterm Examination October 5, 2016 Question Points Score 1 15 2 10 3 10 4 8 5 9 TOTAL 52 SOLUTIONS Your name (Please print) 1. Suppose you are given a singly-linked
More informationCOMP 213 Advanced Object-oriented Programming Lecture 8 The Queue ADT (cont.)
COMP 213 Advanced Object-oriented Programming Lecture 8 The Queue ADT (cont.) Recall: The Queue ADT A data structure in which elements enter at one end and are removed from the opposite end is called a
More information17. Assertions. Jelle Slowack, Bart Smets, Glenn Van Loon, Tom Verheyen
17. Assertions Jelle Slowack, Bart Smets, Glenn Van Loon, Tom Verheyen Outline Introduction (BIT, assertion, executable assertion, why?) Implementation-based vs responsability-based assertions Implementation
More informationPlease note that if you write the mid term in pencil, you will not be allowed to submit a remark request.
University of Toronto CSC148 Introduction to Computer Science Fall 2001 Mid Term Test Section L5101 Duration: 50 minutes Aids allowed: none Make sure that your examination booklet has 8 pages (including
More informationInheritance. Transitivity
Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated
More informationCMP-338 Solutions Midterm Spring Version 1
Version 1 Instructions Write your name and version number on the top of the yellow paper. Answer all questions on the yellow paper. One question per page. Use only one side of the yellow paper. 1. (16
More informationToday's Agenda. References. Open Closed Principle. CS 247: Software Engineering Principles. Object-Oriented Design Principles
CS 247: Software Engineering Principles Reading: none Object-Oriented Design Principles Today's Agenda Object-Oriented Design Principles - characteristics, properties, and advice for making decisions that
More information22c:181 / 55:181 Formal Methods in Software Engineering
22c:181 / 55:181 Formal Methods in Software Engineering Design by Contract Copyright 2001-11, Matt Dwyer, John Hatcliff, Rod Howell, and Cesare Tinelli. Produced by Cesare Tinelli at the University of
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Queues ArrayQueue Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 10, 2014 Abstract These lecture notes are meant to be looked
More informationSoftware Development. Modular Design and Algorithm Analysis
Software Development Modular Design and Algorithm Analysis Precondition and Postcondition To create a good algorithm, a programmer must be able to analyse a precondition (starting state) and a postcondition
More informationCS 215 Software Design Sample Midterm Questions
Software Design 1. The administration at Happy Valley School District is redesigning the software that manages information about its students. It has identified an abstract class Student, with two subclasses:
More informationSymbolic Execution and Proof of Properties
Chapter 7 Symbolic Execution and Proof of Properties Symbolic execution builds predicates that characterize the conditions under which execution paths can be taken and the effect of the execution on program
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More informationJAVA NOTES DATA STRUCTURES AND ALGORITHMS
79 JAVA NOTES DATA STRUCTURES AND ALGORITHMS Terry Marris July 2001 11 QUEUE IMPLEMENTATION - ARRAYS 11.1 LEARNING OUTCOMES By the end of this lesson the student should be able to describe how an array
More informationSeptember 10,
September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible
More informationInheritance and object compatibility
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not the other way around Examples: reference/pointer can
More informationInheritance, Polymorphism, and Interfaces
Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)
More informationLecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning
Lecture 1 Contracts 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,
More informationViolations of the contract are exceptions, and are usually handled by special language constructs. Design by contract
Specification and validation [L&G Ch. 9] Design patterns are a useful way to describe program structure. They provide a guide as to how a program fits together. Another dimension is the responsibilities
More informationCSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.
Name Solution The exam is closed book and closed electronics. One page of notes is allowed. The exam has 6 regular problems and 1 bonus problem. Only the regular problems will count toward your final exam
More informationCS 32. Lecture 1: oops
CS 32 Lecture 1: oops Textbooks Problem Solving in C++ (CS 16) Chapters 10-18 Data Structures with C++ (CS 24) Chapters 12-14 Reader SBPrinter at UCen Grading Labs 20% Programming Assignments 20% 3 thirdterm
More informationCMP Points Total Midterm Spring Version (16 Points) Multiple Choice:
CMP-338 106 Points Total Midterm Spring 2017 Version 1 Instructions Write your name and version number on the top of the yellow paper. Answer all questions on the yellow paper. One question per page. Use
More informationCSE 143 SAMPLE MIDTERM
CSE 143 SAMPLE MIDTERM 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust code
More information03/29/2004. A dispenser has three essential features: adding, removing, accessing. Dispensers
Dispensers stacks queues priority queues Dictionaries A dispenser is a container that restricts access to its elements. Only one element in the container can be accessed or removed. This element is called
More informationJAVA BASICS II. Example: FIFO
JAVA BASICS II Example: FIFO To show how simple data structures are built without pointers, we ll build a doubly-linked list ListItem class has some user data first refers to that ListItem object at the
More informationOutline. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Benefits of Subtype Polymorphism. Subtype Polymorphism
Subtype, Subtyping vs. Subclassing, Liskov Substitution Principle Outline Subtype polymorphism Subtyping vs. subclassing Liskov Substitution Principle (LSP) Function subtyping Java subtyping Composition:
More informationTest-Driven Development (TDD)
Test-Driven Development (TDD) EECS3311 A: Software Design Fall 2018 CHEN-WEI WANG DbC: Supplier DbC is supported natively in Eiffel for supplier: class ACCOUNT create make feature -- Attributes owner :
More informationIntroduction to Object-Oriented Programming
Introduction to Object-Oriented Programming Inheritance, Part 2 of 2 Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Inheritance, Part 2 of 2 1 / 14 Access Modifiers Modifier Class
More informationCMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012
CMPSCI 187: Programming With Data Structures Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 Implementing Stacks With Arrays The Idea of the Implementation Data Fields
More informationA Short Summary of Javali
A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler
More informationChapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.
Chapter 13 Object Oriented Programming Contents 13.1 Prelude: Abstract Data Types 13.2 The Object Model 13.4 Java 13.1 Prelude: Abstract Data Types Imperative programming paradigm Algorithms + Data Structures
More informationAspect-oriented programming with AspectJ. The building blocks of AspectJ: Join points, pointcuts and advices
Aspect-oriented programming with AspectJ Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Quebec Canada August 11, 2016 1 / 124 The building
More information6.170 Recitation #5: Subtypes and Inheritance
6.170 Recitation #5: Subtypes and Inheritance What is true subtyping? True Subtyping is not exactly the same as Inheritance. As seen in an earlier lecture, class A is a true subtype of class B if and only
More informationLecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning
Lecture 1 Contracts 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,
More informationDesign by Contract: An Overview
: An Overview CSCI 5828 Michael M. Vitousek University of Colorado at Boulder michael.vitousek@colorado.edu March 21, 2012 1 / 35 Outline 1 Introduction Motivation and Introduction Simple Example Contract
More informationCS 216 Exam 1 Fall SOLUTION
CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT
More information1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides
1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of
More informationThe Java Modeling Language (Part 2)
The Java Modeling Language (Part 2) Wolfgang Schreiner Wolfgang.Schreiner@risc.jku.at Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria http://www.risc.jku.at
More informationIndex. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107
A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105
More informationAssertions, pre/postconditions
Programming as a contract Assertions, pre/postconditions Assertions: Section 4.2 in Savitch (p. 239) Specifying what each method does q Specify it in a comment before method's header Precondition q What
More informationAssociate Professor Dr. Raed Ibraheem Hamed
Associate Professor Dr. Raed Ibraheem Hamed University of Human Development, College of Science and Technology Computer Science Department 2015 2016 1 What this Lecture is about: Stack Structure Stack
More informationCS18000: Programming I
CS18000: Programming I Data Abstraction January 25, 2010 Prof. Chris Clifton Announcements Book is available (Draft 2.0) Syllabus updated with readings corresponding to new edition Lab consulting hours
More informationAdvances in Programming Languages
O T Y H Advances in Programming Languages APL8: ESC/Java2 David Aspinall (including slides by Ian Stark and material adapted from ESC/Java2 tutorial by David Cok, Joe Kiniry and Erik Poll) School of Informatics
More informationProgramming By Contract: Designing for Correctness
Programming By Contract: Designing for Correctness James C. McKim, Jr. Rensselaer, 1999 1 of 20 Overview What is Programming by Contract? How do we use Programming by Contract to design correct classes?
More information+ Abstract Data Types
Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract
More informationHoare Logic: Proving Programs Correct
Hoare Logic: Proving Programs Correct 17-654/17-765 Analysis of Software Artifacts Jonathan Aldrich Reading: C.A.R. Hoare, An Axiomatic Basis for Computer Programming Some presentation ideas from a lecture
More informationUNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED
UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance
More informationObject Oriented Program Correctness with OOSimL
Kennesaw State University DigitalCommons@Kennesaw State University Faculty Publications 12-2009 Object Oriented Program Correctness with OOSimL José M. Garrido Kennesaw State University, jgarrido@kennesaw.edu
More informationCT 229 Object-Oriented Programming Continued
CT 229 Object-Oriented Programming Continued 24/11/2006 CT229 Summary - Inheritance Inheritance is the ability of a class to use the attributes and methods of another class while adding its own functionality
More informationCS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and
More informationA Correctness Proof for a Practical Byzantine-Fault-Tolerant Replication Algorithm
Appears as Technical Memo MIT/LCS/TM-590, MIT Laboratory for Computer Science, June 1999 A Correctness Proof for a Practical Byzantine-Fault-Tolerant Replication Algorithm Miguel Castro and Barbara Liskov
More informationAn Approach to Behavioral Subtyping Based on Static Analysis
TACoS 04 Preliminary Version An Approach to Behavioral Subtyping Based on Static Analysis Francesco Logozzo 1 STIX - École Polytechnique F-91128 Palaiseau, France Abstract In mainstream object oriented
More informationTutorial notes on. Object relational structural patterns
Tutorial notes on Object relational structural patterns Dr. C. Constantinides, P.Eng. Computer Science and Software Engineering Concordia University Page 1 of 14 Exercise 1. a) Briefly describe what is
More informationUse the scantron sheet to enter the answer to questions (pages 1-6)
Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object
More informationPractice for Chapter 11
Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing
More informationToday s lecture. CS 314 fall 01 C++ 1, page 1
Today s lecture Midterm Thursday, October 25, 6:10-7:30pm general information, conflicts Object oriented programming Abstract data types (ADT) Object oriented design C++ classes CS 314 fall 01 C++ 1, page
More informationDATA TYPES. CS 403: Types and Classes DATA TYPES (CONT D)
DATA TYPES CS 403: Types and Classes Stefan D. Bruda Fall 2017 Algorithms + data structures = programs Abstractions of data entities highly desirable Program semantics embedded in data types Data types
More informationMidterm Exam 2 CS 455, Spring 2011
Name: USC loginid (e.g., ttrojan): Midterm Exam 2 CS 455, Spring 2011 March 31, 2011 There are 6 problems on the exam, with 50 points total available. There are 7 pages to the exam, including this one;
More informationECSE 321 Assignment 2
ECSE 321 Assignment 2 Instructions: This assignment is worth a total of 40 marks. The assignment is due by noon (12pm) on Friday, April 5th 2013. The preferred method of submission is to submit a written
More informationCS171 Midterm Exam. October 29, Name:
CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and
More informationJML Class Specifications The Java Modeling Language (Part 2) A Java Class
JML Class Specifications The Java Modeling Language (Part 2) Wolfgang Schreiner Wolfgang.Schreiner@risc.jku.at Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria
More informationInheritance and Interfaces
Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical
More informationCosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs
1 Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs Michael Albert michael.albert@cs.otago.ac.nz Keywords: abstract data type, collection, generic class type, stack 2 Collections
More information