Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Similar documents
Last name:... First name:... Department (if not D-INFK):...

Conformance. Object-Oriented Programming Spring 2015

Last name:... First name:... Department (if not D-INFK):...

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Type Hierarchy. Lecture 6: OOP, autumn 2003

Exercise 13 Self-Study Exercise Sheet

Object Oriented Issues in VDM++

Exercise 10 Object Structures and Aliasing November 27, 2015

6.170 Recitation #5: Subtypes and Inheritance

Exercise 13 Self-Study Exercise Sheet

Assertions. Assertions - Example

CSE341, Fall 2011, Lecture 26 Summary

Object typing and subtypes

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

Exercise 10 Aliasing and Readonly Types December 1, 2017

CS 161 Computer Security

JAVA BASICS II. Example: FIFO

CIS 120 Final Exam 15 December 2017

Program Verification (6EC version only)

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Exercise 8 Parametric polymorphism November 17, 2017

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

CSE 331 Final Exam 3/12/12

Testing, Debugging, and Verification

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

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

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

Jam: A Smooth Extension With Java Mixins

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

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

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 3, 2017

Safely Creating Correct Subclasses without Seeing Superclass Code

Exercise 8 Parametric polymorphism November 18, 2016

INSTRUCTIONS TO CANDIDATES

Assertions, pre/postconditions

Universe Type System for Eiffel. Annetta Schaad

CSE 331 Final Exam 12/14/15 Sample Solution. Question 1. (20 points, 1 each) Warmup. For each statement, circle T if it is true and F if it is false.

CSE 331 Midterm Exam Sample Solution 2/18/15

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM

Announcements. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Intuition: Type Signature is a Specification.

CSCE 314 Programming Languages

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

What is a type? Types in OO languages. What is a type? Types as sets. Example. Clients of screensaver

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

EXAMINATIONS 2009 MID-TERM TEST. COMP 202 / SWEN 202 Formal Methods of Computer Science / Formal Foundations of Software Engineering WITH ANSWERS

Name: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron

Comparing procedure specifications

8 Understanding Subtyping

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

CSE 331 Midterm Exam 11/9/15 Sample Solution

CSE 331 Final Exam 3/16/15 Sample Solution

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

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

EXAMINATIONS 2012 END-OF-YEAR SWEN222. Software Design. Question Topic Marks 1. Design Quality Design Patterns Design by Contract 12

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 3, 2017

Chapter 10 Classes Continued. Fundamentals of Java

21 Subtyping and Parameterized Types

Safely Creating Correct Subclasses without Seeing Superclass Code

Lecture 10 Design by Contract

JML Class Specifications The Java Modeling Language (Part 2) A Java Class

Advanced JML Erik Poll Radboud University Nijmegen

Recap. What is a type? Types in OO languages. What is a type? Types as sets. Up next, some advanced OO topics

Prelim 1. CS 2110, March 15, 2016, 5:30 PM Total Question Name True False. Short Answer

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

The Java Modeling Language (Part 2)

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

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

Concepts of Object-Oriented Programming Peter Müller

A New Formalization of Subtyping to Match Subclasses to Subtypes

Final exam. CS 2110, December 15, 2016, 9:00AM

Inheritance (Part 5) Odds and ends

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

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

Prelim 1. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

A Run-time Assertion Checker for Java using JML

CSC Advanced Object Oriented Programming, Spring Specification

Specification tips and pitfalls

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

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Prelim 1. CS 2110, March 15, 2016, 7:30 PM Total Question Name True False. Short Answer

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

EINDHOVEN UNIVERSITY OF TECHNOLOGY

CSE wi Midterm Exam 2/8/18. Name UW ID #

Collections Algorithms

Declarations and Access Control SCJP tips

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Subtypes and Subclasses

Object Oriented Programming. Java-Lecture 11 Polymorphism

Formal Methods for Java

University of Washington CSE 331 Software Design & Implementation Spring Final exam. Monday, June 10, 2013

CSE331 Winter 2014, Final Examination March 17, 2014 Please do not turn the page until 8:30. Rules:

Java Object Oriented Design. CSC207 Fall 2014

Transcription:

Concepts of Object-Oriented Programming AS 2017 Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017 Task 1 In this question, we are in a nominal subtyping setting. Some languages have a special type MyType that represents the dynamic type of this object. (a) Consider the following code: class Point int x,y; boolean equals(mytype other) return x == other.x && y == other.y; class ColorPoint extends Point int color; override boolean equals(mytype other) return super.equals(other) && color == other.color; This definition requires that the dynamic type of the parameter of equals is a subtype of the dynamic type of this. Consider the following definitions that give static types to some variables: Point p; ColorPoint cp1, cp2; and the following calls: p.equals(cp1) // A p.equals(cp2) // B cp1.equals(p) // C cp2.equals(cp1) // D cp1.equals(cp2) // E Assume a sound, statically-checked type system. Which of the calls above must be forbidden and which may be allowed? Why? All calls are potentially unsafe and should be forbidden. The reason is that the dynamic type of both the receiver and the parameter are unknown and are not guaranteed to match the restriction that the dynamic type of the parameter should be a subtype of the dynamic type of the receiver.

(b) Answer the same question, assuming that ColorPoint is final, i.e., we may not declare new classes as its subtypes. In this case, we know that the dynamic types of both cp1 and cp2 are ColorPoint. This guarantees that the calls D and E are ok. However, the first three calls remain unsafe. The first two calls are unsafe because the dynamic type of p may be of a subtype of Point that has no relation to ColorPoint. The C call is not safe, because p may have the dynamic type Point. (c) Assume now that the language includes the feature of exact types. An exact type is written @C where C is a normal type. When we declare that an object o is of type @C, then o is of type C, but does not belong to any of the other subtypes of C. Assume that the definitions of our variables are changed as follows: @Point p; @ColorPoint cp1; ColorPoint cp2; and do not assume that ColorPoint is final. Why? Which calls should be forbidden now? All is known about the dynamic types of cp1 and p. The calls A, B, and E are safe. D is not, because cp2 may belong to a proper subtype of ColorPoint. C is not, because p is of dynamic type Point. Hint. The classes shown here may be subclassed in code that is not available. The type-checker cannot make the assumption that there are no other class definitions elsewhere. Task 2 Let SortedArray be a Java class, which has a private field A. The field A must be a sorted (in increasing order) array of integers with no duplicates. The following method inserts a value into the array: void insert (int x) int[] B = new int[a.length + 1]; int i = 0; while (i < A.length && A[i] < x) B[i] = A[i]; i++; B[i] = x; while (i < A.length) B[i+1] = A[i]; i++; A = B; Give an appropriate invariant for the class, as well as a precondition and a postcondition for the method insert. You may use quantifiers (, ) in your annotations. Note that the invariant is automatically checked at the end of the method body and you do not need to explicitly include it in the postcondition.

Hint: Consider what happens when the item to be inserted into the array already exists. Do not change the implementation to avoid this situation. class sortedarray int[] A; /// invariant A null /// invariant i:int 0 i i < A.length-1 A[i] < A[i+1] /// requires i:int 0 i i < A.length x A[i] /// ensures A.length = old(a.length) + 1 /// ensures /// i0:int /// (0 i0 i0 < A.length) /// A[i0] = x /// ( i:int (0 i i < i0 A[i] = old(a[i])) /// ( i:int (i0 < i i < A.length A[i] = old(a[i-1])) void insert (int x)... Another approach to express the specification of insert is as follows: first, we introduce an auxiliary function contains: contains(l, x) = j:int (0 j j < L.length L[j] = x) Using contains we can express the specifications of insert as follows: requires contains(a, x) ensures i:int contains(a, i) (i = x contains(old(a), i)) Task 3 Alice and Bob are two software developers. Alice is writing a small class Cell that stores an integer. The class supports methods for setting/getting/increasing the integer. Bob is going to write code that uses the class Cell. Here are the contracts of the methods (the bodies are omitted): class Cell public int n; // this field is public for simplicity // generally this is not a recommended practice /// requires true /// ensures n == p public void set(int p)... /// requires true /// ensures result == n public int get()... /// requires true /// ensures n > old(n) public void inc()... In this exercise we will experiment with modifying the specifications. In particular, if we modify a specification, this might become:

more restrictive for a party. For example, a specification that is more restrictive for Alice might not allow some implementations that were OK with the old specification. A specification that is more restrictive for Bob might mean that a piece of code that Bob wrote cannot guarantee something that it had guaranteed before. more flexible for a party. If a specification S is more flexible than a specification S for a party P, then S is more restrictive than S for P. it might be the case that the new specification is neither more restrictive nor more flexible for a party. For example, the new specification makes some previously correct code illegal, while it also makes some previously illegal code correct. For example, if we modify the postcondition of get such that: result == n result == -n the specification becomes more flexible for Alice, because she is allowed the, previously illegal, implementation of get: return n > 5? n : -n; while, at the same time, it becomes more restrictive for Bob, because the following code c.set(3); x = c.get(); does not guarantee the postcondition x == 3 anymore. For each of the following specification changes (subtasks a-d), do the following: (i) Write formally the new pre/postconditions (not invariants). Only write the pre/postconditions that change. (ii) Compare the flexibility of the new specifications to the old ones, from the point of view of both Alice and Bob. (iii) Justify your answers for both parties by providing code. Note that a postcondition should be satisfiable for any valid pre-state. You can assume that the implementation of the methods do not call each other. (a) It is only allowed to set n to a strictly positive value. This amounts to adding the precondition p > 0 to set. This specification is more flexible for Alice, for example the following, previously incorrect, implementation is now valid: if(p > 0) n = p; On the other hand, this is more restrictive for Bob, because the code c.set(-1); is not allowed by the new precondition anymore. (b) inc should increase n by exactly one. This conjoins the postcondition n == old(n) + 1 to inc. Alice is more restricted: she cannot do this anymore: n = n + 2;

Bob is more flexible. Now c.set(4); c.inc(); x = c.get(); guarantees the postcondition x == 5, which it didn t before. (c) inc should increase n by any amount, but it should guarantee that the final value of n is strictly positive. This conjoins the postcondition n > 0 to inc. The implementation from (b) still does not work for Alice, who is more restricted. Bob, on the other hand, is more flexible: c.inc(); x = c.get(); guarantees the postcondition x > 0. (d) inc should increase n by exactly one and should guarantee that the final value of n is strictly positive. If necessary, add preconditions to ensure that it is possible for Alice to achieve this goal. This conjoins the postcondition n > 0 && n == old(n) + 1 to inc. However, for this to be implementable, inc should also have a precondition n >= 0. (Note that adding this precondition makes the conjunct n > 0 in the postcondition obsolete). This restricts Alice again (the implementation from (b) is not acceptable). However, now Bob is also restricted. The following code is not allowed by the new precondition anymore: c.set(-2); c.inc(); On the other hand Alice also gains some flexibility! For example, one possible implementation of inc which would have not been valid before is: if(n > -10) n = n + 1; Bob also gains some flexibility. Bob s code from case (b) guarantees the postcondition x == 5. Task 4 (from a previous exam) Assume we add an otherwise clause to method contracts in Java, which gives a condition on the state after the method throws an exception. The implementation of the method has to guarantee that the condition in the otherwise clause is true whenever the method returns exceptionally (that is, via throwing an exception). Consider a class with an integer field f and the following Java method and its precondition and an otherwise-clause (reminder: final parameters cannot be assigned to): /// requires n > 0 /// otherwise f < 0 void foo(final int n) throws IOException Assume method foo is overridden in a subclass and that we do not use specification inheritance. Which of the following functions...

1.... override foo correctly based on the variance rules of Java and 2.... have preconditions and otherwise-clauses that would be allowed if the subclass should be a behavioral subtype? For this, decide what kind of relationship between otherwise-clauses of behavioral subtypes should exist, basing your decision on the substitution principle. For this exercise, assume FileNotFoundException <: IOException <: Exception and that there is no integer overflow. (a) requires n == 0 otherwise f == -1 void foo(final int n) throws FileNotFoundException (b) requires n > 0 otherwise f * f > 0 void foo(final int n) throws IOException (c) requires n >= 0 otherwise f < -n void foo(final int n) throws Exception (d) CORRECT: requires n!= 0 otherwise f == -n void foo(final int n) throws IOException (e) None of the above would be allowed Would your answer be the same if n were not final? Exceptions have to be covariant, so (c) cannot be the right answer. For behavioral subtyping, otherwise-clauses should respect the same rules as postconditions. Namely, overriding methods of subtypes may have stronger otherwise-clauses than corresponding supertype methods. Pre super Pre sub old(p re super ) (P ost sub P ost super ) Behavioral subtyping a no yes no b yes no no d yes yes yes If n were not final, the right answer would still be (d). Parameter references in postconditions always refer to the value that was originally passed, so it would not make any difference if n were not final. Task 5 Assume a language with structural subtyping, contravariant arguments, and covariant return types. Is it possible to create the classes A, B, and C that meet all of the following requirements? 1. B is a structural subtype of A, and C is a structural subtype of B. 2. B is not a behavioral subtype of A. 3. C is a behavioral subtype of both A and B.

4. The signatures of any two methods of A, B, or C should be different. For this exercise the signature is the combination of return type, method name, and argument order and types. Note that different signatures do not preclude structural subtyping. 5. The classes do not have any fields. If it is possible to meet all the above requirements, write the classes A, B, and C. If it is not possible to meet all the requirements, explain why not. Then pick a requirement and remove it. Write down the classes A, B, and C that meet the remaining four requirements. In both cases specify the behavior of the classes using contracts. You do not need to provide method bodies. You may use existing Java classes in your, if you want to. All requirements can be met. Here are the corresponding classes: class A ///requires a > 0 ///ensures result > 0 Number foo(integer a) class B ///requires a > 10 ///ensures result > 0 Number foo(number a) class C ///requires true ///ensures result == 10 result == 20 Integer foo(object o)