Adding Contracts to C#

Size: px
Start display at page:

Download "Adding Contracts to C#"

Transcription

1 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 must have built in support for pre conditions, post conditions and class invariants, collectively called contracts, or some mechanism must be devised to validate the contract. This paper proposes a way of supporting contracts in C# using Resolve Corp. s extensible C# add in. Keywords Design by Contract, C#, extensible C# 1. INTRODUCTION Design by contract is a software engineering technique used to promote software reliability. This idea was made popular by Bertrand Meyer and his work on the Eiffel programming language [4]. The main idea behind design by contract is that for a routine to work properly a set of conditions must hold true before the routine is called, the pre conditions, and another set of conditions must hold true after the routine has finished its task, the post conditions. The conditions are checked using assertions and an assertion failure indicates a bug in the program. A pre condition assertion failure indicates that the bug is in the program that called the routine, while a post condition assertion failure indicates that the bug is in the routine itself. Additionally, when used in an object oriented programming language, there is a set of conditions that apply to the class of objects that must hold true for the life of the object. These conditions are called class invariants or simply invariants. The invariants are checked with the pre conditions and the post conditions on all methods that can be called from another object. An invariant assertion failure indicates a problem in the class and specifically to the routine being executed when the assertion occurred. In order to use design by contract the selected programming language must have built in support for pre conditions, post conditions and class invariants, collectively called contracts. However, only a few programming languages have built in support for contract, Eiffel being one of them. For all other languages, some mechanism must be devised in order to inject the assertion checks into methods needed to validate the contract. For C++ and Java, several mechanisms have been devised to support design by contract [1, 2, 7]. These range from using special comments and the pre processor to inheriting from a special class and embedding the contract assertions in the methods. Neither of these options will work for the C# language since there is no pre processor and only single inheritance is supported. Some mechanisms for the C# language that are a good starting point, but fail to deliver on the full idea of design by contract have been tried. One is a helper class [3] to handle the contract assertions, but there is no automatic support for inheritance. Another is a post compilation Visual Studio add in [9] that uses custom attributes to specify the contract assertions. The use of custom attributes supports inheritance, but it does not work when a class implements an interface. Additionally, the use of Eiffel s old and implies keywords are not supported. Finally, there is a proposal to modify the common language infrastructure to support contracts [8], but that is not currently supported in the C# language. There has been work on creating a separate program to add contracts to existing assemblies [5]. This program uses Eiffel classes to wrap the classes from the assembly with contracts and to that extent it is effective. However, this process is done after the assembly is built and there is no support specifying the contract assertions in the code itself. It was noted in the future work section of the paper that they are exploring the use of custom attributes to specify the contract assertions in the code. 2. Specifying the Contracts In the.net family of languages, metadata is used to store information about the program. The metadata contains information about the assembly (DLL or executable) and the types (classes, structures, enumerations, etc.) contained in the assembly along with associated attributes. The attribute metadata is used to add additional information to types or the type members. This additional information can then be used to modify the behavior of the program at runtime or, in the case of adding contracts to C#, insert assertion checks into methods and properties. 2.1 Design by Contract Attributes Each of the assertion types are specified using the same format. The first parameter is a string which is used as the label for the assertion. In the case where the assertion is not met, the label is used as the message to the user indicating what has happened. The second parameter is a string containing the assertion condition. Pre conditions use the DBCRequire attribute, post conditions use the DBCEnsure attribute and invariants use the DBCInvariant attribute. The pre condition and post condition attributes are placed directly before the method or property to which they apply and the invariant attribute is placed directly before the class, structure or interface to which it applies. Figure 1 shows an example of a simple stack interface. The last attribute used is the DBCEnable attribute. This attribute is used to specify which types of assertions are used and how the assertions are implemented. The enable attribute can be used at the assembly level, class level or method level. There are several ways of specifying the enable attribute. The easiest way is to use the enable attribute is to pass a Boolean which indicates whether the assembly is being built for release or for testing. When the value is false, all assertion types are enabled and are implemented using an Assert statement. When the value is true, only the pre condition assertions are enabled and they are implemented using an exception. The main difference between the Assert statement and exceptions is that the Assert statement stops program execution at the Assert statement line. An exception, on the other hand, is thrown when there is a problem and program execution starts rolling back until the first exception handler is found. The SC2-T1-1

2 [DBCInvariant("Valid Count", "(Count >= 0) && (Count <= Capacity)")] public interface IStack { [DBCEnable(InvariantDisabled=true)] int Capacity { get; } [DBCEnable(InvariantDisabled=true)] int Count { get; } [DBCEnsure("Result Matches Count", "result == (Count == 0)")] bool IsEmpty { get; } [DBCEnsure("Result Matches Count", "result == (Count == Capacity)")] bool IsFull { get; } [DBCRequire("Not Empty", "! IsEmpty")] object Top { get; } [DBCRequire("Not Full", "! IsFull")] [DBCEnsure("New Top", "! old IsFull implies Top.Equals(value)")] [DBCEnsure("New Count", "! old IsFull implies Count == old Count+1")] void Push( object value ); } [DBCRequire("Not Empty", "! IsEmpty")] [DBCEnsure("New Count", "! old IsEmpty implies Count == old Count-1")] void Pop(); exception provides a graceful way of handling and correcting errors. In addition to, or instead of, passing a Boolean value to the enable attribute, one or more of the properties of the enable attribute can be used. Each contract assertion type has three properties; assertiontypeassert, assertiontypeexception and assertiontypedisabled where assertiontype is PreCondition, PostCondition or Invariant. The Capacity and Count properties in Figure 1 show that the invariant assertions are disabled for these properties only. 2.2 Building With extensible C# Once the contract is specified using attributes, which is stored in the metadata, there needs to be a way of getting the contracts into the code. To do this, Resolve Corp. s extensible C# add in [9] is used. extensible C# is a program that integrates with Microsoft s Visual Studio development environment. When it is enabled, the add in waits for the development environment to successfully build an assembly and then injects code into the assembly based on specific attributes. The add in allows users to all additional attributes to its set of predefined attributes which is what the authors of this paper did. The technique used by the extensible C# add in to inject code into the assembly is as follows: 1. Process each type (class, structure) in the assembly. 2. Process each member (method, property) in each type. Figure 1. Sample C# stack interface with contracts. 3. Get the attributes associated with the member and inject code into the member. The first step of the process is handled by the add in and is not accessible to the writers of custom attributes. However, the authors of this paper handle the second and third steps of the procedure. There are two places that the design by contract assertions gets injected into methods or properties. The first place is before the first statement of the method or property as defined by the source code. The second is at any return statement, or in the absence of a return statement, after the last statement of the method or property as defined by the source code. Pre condition assertions and the storing of values specified by the old keyword of post condition assertions are placed at the beginning of the method or property. Also, if the method or property is non private and is not a constructor, invariant assertions are placed at the beginning of the method or property. Post condition assertions, and if the method or property is non private, invariant assertions are placed at the end of the method or property or at each return statement. When a return statement is encountered it is replaced with a new block of code. This block of code first stores the value being returned in a result keyword variable. Next any post condition and invariant assertion code is added. Finally, the stored result value is returned. 3. Inheritance Another of the basic principles of design by contract is that a class inherits its contracts from its base class. This should not be SC2-T1-2

3 surprising for anyone familiar with object oriented programming since a class inherits its members and functionally from its base class. There are a few simple rules that must be followed when changing a contract in a derived class. The first is that when a subclass modifies a pre condition, it can only weaken the assertion to make it less restrictive. The weakening of a condition can be viewed as logically OR ing the conditions. The second is that when a subclass modifies a post condition or invariant, it can only strengthen the assertion to make it more restrictive. The strengthening of a condition can be viewed as logically AND ing the conditions. Since the post conditions and invariants can only be strengthened, the authors of this paper did not need to anything to enforce this requirement. That is because in a strengthened condition, all parts of the condition must pass the assertion check. Checking each part of the condition separately is equivalent to checking each part of the condition AND ed together. On the other hand, since pre conditions can only be weakened, the authors of this paper needed a way of enforcing this requirement. The technique used is to combine all pre conditions for a given method or property that have the same label using the logical OR operator. 3.1 Inheritance in C# C# only supports single inheritance, but it allows a class to implement multiple interfaces. An interface defines a type that has methods and/or properties, but does not have any executable code. When a class implements an interface, it implements all the methods and properties defined in the interface. The class designer has a choice when implementing each method and property of an interface. The class designer can choose to directly implement the method or property so it is accessible from both the class reference and the interface reference. The class designer can alternatively choose to implement the method or property so that it is only accessible from an interface reference. When a class implements an interface, the class is also bound by the contract defined in the interface. This means that all pre conditions and post conditions on methods and properties defined in the interface apply to the class implementation of those methods and properties. Also, all invariants defined in the interface become invariants of the class. But what happens when a class implements two interfaces that share a common method? The answer is it depends on how the class implements the common method. If the class uses a single implementation of the method for both interfaces, then the pre conditions and post conditions from both interfaces are applied to the class method. If the class uses separate methods for each interface method, then only the pre conditions and post conditions from the proper interface are applied to the class method. 4. Test Cases In order to properly determine whether or not contracts can be used in C#, a set of test cases were developed. The test cases were designed to exercise the capabilities of design by contract in a variety of structural situations. Several of the test cases were taken from the examples provided by [6] and adapted for the C# language. The first test case (TC1) used a single class that defined a contract. The second test case (TC2) used an abstract base class that defined a contract and two derived classes. The first derived class simply used the contract inherited from the abstract base class. The second derived class used the contract inherited from the abstract base class and modified the contract for two methods, making the second derived class easier to use. The third test case (TC3) used an interface that defined a contract and two classes that implement the interface. As in TC2, one class used the contract from the interface without modification and the second class made modifications to the contract. The fourth test case (TC4) used multiple interfaces, each defining their own contract, and a single class that implemented both interfaces. The interfaces did not have any methods or properties in common. The fifth test case (TC5) used multiple interfaces that shared a common method. Two classes implemented both interfaces where the first class used a single method to implement the common interface methods and the second class used two methods to implement the common interface methods. Finally, the sixth test case (TC6), in order to get more than one level of inheritance, used an interface that defined a contract, an abstract class that implemented the interface and modified the contract and a derived class the inherited from the abstract class. While compiling TC5, a minor problem was encountered. The two interfaces had a method in common and the class implemented the common method using separate methods. However, when this is done, the method is not accessible when using a reference to the class; it is only accessible using a reference to the interface. Since the interface defined the contract using the method and property names only, this is seen by the compiler as going through the class reference. And since the method common to both interfaces is not accessible through a reference to the class, the compiler generated errors. The solution was to modify the way the interfaces defined their contracts. Instead of using a property or method name directly, the name needed to be qualified as being part of the interface. As an example, the expression from the ISet interface changed from to Has(value) ((ISet) this).has(value) this in C# is a keyword for the reference to the class. It is then cast to be a reference to the interface. Another issue that appeared during development was a stack overflow when invariants were part of the contract. By definition, invariants are to be checked before and after every non private method or property. This includes the methods and properties that are used by the invariant assertion checks. Since the assertion checks are implemented by injection code into the methods and properties, there is no way to ignore the checks when a method is entered multiple times. This is what caused the stack overflow problem. To get around the problem, the invariant checks are disabled for the methods and properties involved in the checks by using the DBCEnable attribute. 5. Test Procedure and Results In order to test the effectiveness of design by contract in C#, a combination of methods was used. First, a test program was used to exercise the above test cases. The test program was used as a general check of the test cases and the pre conditions. Also, with SC2-T1-3

4 changes to the test cases, the post conditions and invariants were also checked. This verified that the contracts were properly being enforced. The second test of effectiveness used a.net decompiler tool. This tool reads an assembly s intermediate language (IL) byte codes and displays the information in a human readable format. This tool was used to verify that the proper assertion checks were being placed in the proper locations within the assembly. As defined in the source code, there were a total of 13 invariants, 30 pre conditions or which 4 were redefinitions and 61 post conditions. After the assertion checks were converted to executable code, there were a total of 20 invariants, 38 pre conditions and 87 post conditions. The second set of numbers is larger because there are several classes that inherited contracts. As seen in Table 1 and Table 2, all of the contract assertions that were defined in interfaces and all of the contract assertions that were defined in abstract base classes made it into the derived classes, with two notable exceptions discussed in the next paragraph. Also, any contract additions or modifications also made it into the derived classes. In TC2 and TC6, the abstract class defined a post condition on its constructor. These post conditions were not inherited by the derived classes because in C# a derived class cannot inherit a constructor. Instead, a derived class constructor calls a base class constructor before executing any code in the derived class constructor. This means that any post conditions defined in a base class constructor must be satisfied before any code from the derived class constructor is executed. However, with proper class design of encapsulation, this is normally not a problem. Table 1 Contract assertions as defined in source code ( in TC2 and TC3 redefine 2 pre-conditions). TC1 TC2 TC3 TC4 TC5 TC6 2 2 Invariants Pre Conditions R 2 0 2R Post Conditions Table 2 Contract assertions as seen in executable code. TC1 TC2 TC3 TC4 TC5 TC6 2 2 Invariants Pre Conditions Post Conditions Summary This paper described a technique of adding contracts to C#. Custom attributes are used to specify the pre conditions (DBCRequire), post conditions (DBCEnsure) and class invariants (DBCInvariant). Also, a fourth attribute (DBCEnable) is used to specify the types of assertion checks and how the checks are implemented. These attributes are injected into the executable code using Resolve Corp. s extensible C# add in. This implementation of design by contract supports contracts across class hierarchies as well as interfaces. The use of the old keyword is supported for post conditions to compare values from the before the method or property was called and after the method or property is done executing. Also, the use of the implies keyword is supported for post conditions to conditionally check the assertion. 7. Future Work One area of work to be investigated is how to solve the contract recursion problem. Ideally, all of the public methods and properties that have contracts call private methods and properties to do the actual work while the public versions check the contract. Then the contract assertions could call the private methods and properties, thereby eliminating the recursion. However, this is not possible using the extensible C# add in. SC2-T1-4

5 8. REFERENCES [1] P. Guerreiro, Another mediocre assertion mechanism for C++, 33rd International Conference on Technology of Object-Oriented Languages, TOOLS 33. Proceedings, June, pp , 2000 [2] R. Kramer, icontract the Java design by contract tool, Technology of Object-Oriented Languages, TOOLS 26. Proceedings, Aug, pp , 1998 [3] K. McFarlane, Design by Contract Framework, [Online document] July 1992, [2004 Oct. 18] Available at HTTP: [4] B. Meyer, Applying design by contract', Computer, Oct., pp 40-51, [5] C. Mingins and C. Chan, Building Trust In Third-Party Components Using Component Wrappers In The.NET Frameworks, Proceedings of the Fortieth International Conference on Tools Pacific, 2002, pp [6] R. Mitchell and J. McKim, Design by Contract, by Example, Indianapolis, Indiana: Addison Wesley, 2002 [7] J. Newmarch, Adding contracts to Java, Technology of Object-Oriented Languages, TOOLS 27. Proceedings, Sep, pp 2-7, 1998 [8] N. Tran; C. Mingins; D. Abramson, Design and implementation of assertions for the Common Language Infrastructure, Proc. IEE Software, vol 150, no. 5, Oct., pp , 2003 [9] extensible C# [Online document], [2004 Oct. 18] Available at HTTP: SC2-T1-5

Assertions. Assertions - Example

Assertions. 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 information

References: 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 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 information

Object Oriented Program Correctness with OOSimL

Object 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 information

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

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 information

Building Trust in Third-party Components using Component Wrappers in the.net Frameworks

Building Trust in Third-party Components using Component Wrappers in the.net Frameworks Building Trust in Third-party Components using Component Wrappers in the.net Frameworks Christine A. Mingins, Chee Y. Chan School of Computer Science and Software Engineering Monash University PO Box 197,

More information

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

Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen Erik Poll - JML p.1/39 Overview Assertions Design-by-Contract for Java using JML Contracts and Inheritance Tools for JML Demo

More information

Design by Contract in Eiffel

Design 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 information

Contract Wizard II: Developing a GUI

Contract Wizard II: Developing a GUI Contract Wizard II: Developing a GUI PROJECT PLAN Diploma project Project period 2004-04-26 2004-08-25 Student name Petra Marty Status 9 th semester Email address martypet@student.ethz.ch Supervisor name

More information

Assertions, pre/postconditions

Assertions, 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 information

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

PROCESS 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 information

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

UC 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 information

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

Self-checking software insert specifications about the intent of a system Assertions Reading assignment A. J. Offutt, A Practical System for Mutation Testing: Help for the Common Programmer, Proceedings of the 12th International Conference on Testing Computer Software, Washington,

More information

JAVA BASICS II. Example: FIFO

JAVA 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 information

CSC Advanced Object Oriented Programming, Spring Specification

CSC 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 information

Type 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 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 information

Programming By Contract: Designing for Correctness

Programming 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

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

Index. 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 information

Inheritance. Transitivity

Inheritance. 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 information

Another Mediocre Assertion Mechanism for C++

Another Mediocre Assertion Mechanism for C++ Another Mediocre Assertion Mechanism for C++ Pedro Guerreiro Departamento de Informática Faculdade de Ciências e Tecnologia Universidade Nova de Lisboa P-2825-114 Caparica, Portugal pg@di.fct.unl.pt Copyright

More information

What can go wrong in a Java program while running?

What can go wrong in a Java program while running? Exception Handling See https://docs.oracle.com/javase/tutorial/ essential/exceptions/runtime.html See also other resources available on the module webpage This lecture Summary on polymorphism, multiple

More information

Type Hierarchy. Lecture 6: OOP, autumn 2003

Type 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 information

Contracts. Dr. C. Constantinides. June 5, Department of Computer Science and Software Engineering Concordia University Montreal, Canada 1/71

Contracts. Dr. C. Constantinides. June 5, Department of Computer Science and Software Engineering Concordia University Montreal, Canada 1/71 Contracts Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada June 5, 2018 1/71 Contracts in human affairs In human affairs we form legally

More information

Chapter 4.!Data Abstraction: The Walls! 2011 Pearson Addison-Wesley. All rights reserved 4-1

Chapter 4.!Data Abstraction: The Walls! 2011 Pearson Addison-Wesley. All rights reserved 4-1 Chapter 4!Data Abstraction: The Walls! 2011 Pearson Addison-Wesley. All rights reserved 4-1 2015-09-29 11:44:25 1/45 Chapter-04.pdf (#4) bubblesort(int[] a) { int last = a.length - 1; while (last > 0)

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

The Contract Pattern. Design by contract

The 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 information

Data Abstraction: The Walls

Data Abstraction: The Walls Chapter 4 Data Abstraction: The Walls 2011 Pearson Addison-Wesley. All rights reserved 4-1 Abstract Data Types Modularity Keeps the complexity of a large program manageable by systematically controlling

More information

Static program checking and verification

Static program checking and verification Chair of Software Engineering Software Engineering Prof. Dr. Bertrand Meyer March 2007 June 2007 Slides: Based on KSE06 With kind permission of Peter Müller Static program checking and verification Correctness

More information

Program Verification (6EC version only)

Program Verification (6EC version only) Program Verification (6EC version only) Erik Poll Digital Security Radboud University Nijmegen Overview Program Verification using Verification Condition Generators JML a formal specification language

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Software Development. Modular Design and Algorithm Analysis

Software 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 information

Control flow in Eiffel

Control flow in Eiffel Announcements Assignment will be posted this week.» We ll make sure you have enough time to it! A little more Eiffel, Genericity and ADTs Week 3, Lecture 4 January 16 Section N Review What is the definition

More information

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

A FLEXIBLE STRATEGY FOR EMBEDDING AND CONFIGURING RUN- TIME CONTRACT CHECKS IN.NET COMPONENTS

A FLEXIBLE STRATEGY FOR EMBEDDING AND CONFIGURING RUN- TIME CONTRACT CHECKS IN.NET COMPONENTS International Journal of Software Engineering and Knowledge Engineering World Scientific Publishing Company A FLEXIBLE STRATEGY FOR EMBEDDING AND CONFIGURING RUN- TIME CONTRACT CHECKS IN.NET COMPONENTS

More information

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

UNIT 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 information

Readability [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. 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 information

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

a 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 information

CHAPTER 6 Design by Contract. Literature. When Design by Contract? Why Design By Contract?

CHAPTER 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 information

Wrapping a complex C++ library for Eiffel. FINAL REPORT July 1 st, 2005

Wrapping a complex C++ library for Eiffel. FINAL REPORT July 1 st, 2005 Wrapping a complex C++ library for Eiffel FINAL REPORT July 1 st, 2005 Semester project Student: Supervising Assistant: Supervising Professor: Simon Reinhard simonrei@student.ethz.ch Bernd Schoeller Bertrand

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

Proceedings of the 8 th International Conference on Applied Informatics Eger, Hungary, January 27 30, Vol. 2. pp Virtuoso Virtuality

Proceedings of the 8 th International Conference on Applied Informatics Eger, Hungary, January 27 30, Vol. 2. pp Virtuoso Virtuality Proceedings of the 8 th International Conference on Applied Informatics Eger, Hungary, January 27 30, 2010. Vol. 2. pp. 375 381. Virtuoso Virtuality Marianna Sipos Department of Information Technology,

More information

Universe Type System for Eiffel. Annetta Schaad

Universe Type System for Eiffel. Annetta Schaad Universe Type System for Eiffel Annetta Schaad Semester Project Report Software Component Technology Group Department of Computer Science ETH Zurich http://sct.inf.ethz.ch/ SS 2006 Supervised by: Dipl.-Ing.

More information

September 10,

September 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 information

3. Design by Contract

3. 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 information

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b 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 information

Dynamic Analysis Techniques Part 2

Dynamic Analysis Techniques Part 2 oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 1 Software Design (F28SD2) Dynamic Analysis Techniques Part 2 Andrew Ireland School of Mathematical & Computer Sciences Heriot-Watt University

More information

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

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

CS 617 Object Oriented Systems Lecture 3 Object Abstractions, Encapsulation, Abstract Data Types 3:30-5:00pm Thu, Jan 10

CS 617 Object Oriented Systems Lecture 3 Object Abstractions, Encapsulation, Abstract Data Types 3:30-5:00pm Thu, Jan 10 The Object Abstraction CS 617 Object Oriented Systems Lecture 3 Object Abstractions,, Abstract Data Types 3:30-5:00pm Thu, Jan 10 Rushikesh K Joshi Department of Computer Science and Engineering Indian

More information

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

JML 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 information

With the popularity of the Web and the

With the popularity of the Web and the Cover Feature Behavioral Specification of Distributed Software Component Interfaces Design by contract solves the problem of behavioral specification for classes in an object-oriented program, which will

More information

Object-oriented Programming. Object-oriented Programming

Object-oriented Programming. Object-oriented Programming 2014-06-13 Object-oriented Programming Object-oriented Programming 2014-06-13 Object-oriented Programming 1 Object-oriented Languages object-based: language that supports objects class-based: language

More information

Software Architecture Bertrand Meyer. Lecture 3: Language constructs for modularity and information hiding

Software Architecture Bertrand Meyer. Lecture 3: Language constructs for modularity and information hiding Software Architecture Bertrand Meyer Last update: 3 April 2007 ETH Zurich, March-July 2007 Lecture 3: Language constructs for modularity and information hiding Ilinca Ciupa Overview Review of modularity

More information

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

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University Semantic Analysis CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Role of Semantic Analysis Syntax vs. Semantics: syntax concerns the form of a

More information

C a; C b; C e; int c;

C a; C b; C e; int c; CS1130 section 3, Spring 2012: About the Test 1 Purpose of test The purpose of this test is to check your knowledge of OO as implemented in Java. There is nothing innovative, no deep problem solving, no

More information

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli Identify and overcome the difficulties encountered by students when learning how to program List and explain the software development roles played by students List and explain the phases of the tight spiral

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Introduction to contract programming

Introduction to contract programming Introduction to contract programming Lukasz Ziobroń Nokia Code Dive Community, 2015 Agenda 1 Problematic examples 2 DbC Theory 3 Language support 4 Own C++ DbC implementation 5 Summary Ariane 5 mission

More information

Test-Driven Development (TDD)

Test-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 information

Software Architecture 4. July 2005

Software Architecture 4. July 2005 Chair of Software Engineering Bertrand Meyer Software Architecture 4. July 2005 Name, First name:... I confirm with my signature, that I was able to take this exam under regular conditions and that I have

More information

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES 1 2 13 Exception Handling It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. Franklin Delano Roosevelt O throw away the worser

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Design by Contract: An Overview

Design 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 information

Exploiting Synergy Between Testing and Inferred Partial Specifications

Exploiting Synergy Between Testing and Inferred Partial Specifications Exploiting Synergy Between Testing and Inferred Partial Specifications Tao Xie David Notkin Department of Computer Science & Engineering, University of Washington {taoxie, notkin}@cs.washington.edu Technical

More information

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

Last name:... First name:... Department (if not D-INFK):... Concepts of Object-Oriented Programming AS 2016 Concepts of Object-Oriented Programming Midterm Examination 11.11.2016 Prof. Dr. Peter Müller Last name:................................. First name:.................................

More information

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1 CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Winter 2008 3/11/2008 2002-08 Hal Perkins & UW CSE V-1 Agenda Java virtual machine architecture.class files Class loading Execution engines

More information

Java: advanced object-oriented features

Java: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Packages

More information

Introduction to Eiffel

Introduction to Eiffel Introduction to Eiffel Martin Nordio, Christian Estler ETH Zurich Distributed Software Engineering Lab 1 Overview Part 1: Language Constructs Ø Basics: definition, if then else, expressions, loops and

More information

Testing, Debugging, and Verification

Testing, Debugging, and Verification Testing, Debugging, and Verification Formal Specification, Part II Srinivas Pinisetty 23 November 2017 Introduction Today: Introduction to Dafny: An imperative language with integrated support for formal

More information

Chapter 14. Exception Handling and Event Handling ISBN

Chapter 14. Exception Handling and Event Handling ISBN Chapter 14 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction

More information

Purpose of the Simulated function

Purpose of the Simulated function How to replace recursive functions using stack a http://www.codeproject.com/articles/418776/how 10,661,731 members (57,717 online) a20121248 251 Sign out home articles quick answers discussions features

More information

The Java Modeling Language (Part 2)

The 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 information

Another IS-A Relationship

Another IS-A Relationship Another IS-A Relationship Not all classes share a vertical relationship. Instead, some are supposed to perform the specific methods without a vertical relationship. Consider the class Bird inherited from

More information

Foundations of Software Engineering Design by Contract

Foundations of Software Engineering Design by Contract Foundations of Software Engineering Fall 2017 Department of Computer Science Ben-Gurion university Based on slides of: Mira Balaban Department of Computer Science Ben-Gurion university R. Mitchell and

More information

Motivation. Correct and maintainable software Cost effective software production Implicit assumptions easily broken

Motivation. Correct and maintainable software Cost effective software production Implicit assumptions easily broken Spec# Andreas Vida Motivation Correct and maintainable software Cost effective software production Implicit assumptions easily broken Need more formal f specification Integration into a popular language

More information

CS4215 Programming Language Implementation

CS4215 Programming Language Implementation CS4215 Programming Language Implementation You have 45 minutes to complete the exam. Use a B2 pencil to fill up the provided MCQ form. Leave Section A blank. Fill up Sections B and C. After finishing,

More information

Java 5. Lecture 33: Java 5. Generics Finally Added. Constrained Genericity

Java 5. Lecture 33: Java 5. Generics Finally Added. Constrained Genericity Java 5 Lecture 33: Java 5 CSC 131 Fall, 2014 Kim Bruce Generics Enhanced for loop (w/iterators) Auto-boxing and unboxing of primitive types Type-safe enumerated types Static Import Simpler I/O Now on Java

More information

Exceptions. Gunnar Gotshalks EX 1

Exceptions. Gunnar Gotshalks EX 1 Exceptions EX 1 Exceptions Are surprising events that occur during the execution of a program» Not surprising that exceptions may occur > so we can prepare for them in a general way» Surprising in that

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

Subclassing for ADTs Implementation

Subclassing for ADTs Implementation Object-Oriented Design Lecture 8 CS 3500 Fall 2009 (Pucella) Tuesday, Oct 6, 2009 Subclassing for ADTs Implementation An interesting use of subclassing is to implement some forms of ADTs more cleanly,

More information

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

(800) Toll Free (804) Fax   Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days Course Description This course introduces the Java programming language and how to develop Java applications using Eclipse 3.0. Students learn the syntax of the Java programming language, object-oriented

More information

22c:181 / 55:181 Formal Methods in Software Engineering

22c: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 information

An Assertion Checking Wrapper Design for Java

An Assertion Checking Wrapper Design for Java An Assertion Checking Wrapper Design for Java Roy Patrick Tan Department of Computer Science Virginia Tech 660 McBryde Hall, Mail Stop 0106 Blacksburg, VA 24061, USA rtan@vt.edu Stephen H. Edwards Department

More information

Traditional Error Handling

Traditional Error Handling Exception Handling 1 Traditional Error Handling We have already covered several mechanisms for handling errors in C++. We ll quickly review them here. Returning Error Values One classic approach involves

More information

C#: advanced object-oriented features

C#: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Namespaces

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecturer: Raman Ramsin Lecture 15: Object-Oriented Principles 1 Open Closed Principle (OCP) Classes should be open for extension but closed for modification. OCP states that we should

More information

C#: advanced object-oriented features

C#: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Namespaces

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

Fortgeschrittene 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 information

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method

More information

Queues. CITS2200 Data Structures and Algorithms. Topic 5

Queues. CITS2200 Data Structures and Algorithms. Topic 5 CITS2200 Data Structures and Algorithms Topic 5 Queues Implementations of the Queue ADT Queue specification Queue interface Block (array) representations of queues Recursive (linked) representations of

More information

Designing Robust Classes

Designing Robust Classes Designing Robust Classes Learning Goals You must be able to:! specify a robust data abstraction! implement a robust class! design robust software! use Java exceptions Specifications and Implementations

More information

An Introduction to Object Orientation

An Introduction to Object Orientation An Introduction to Object Orientation Rushikesh K Joshi Indian Institute of Technology Bombay rkj@cse.iitb.ac.in A talk given at Islampur Abstractions in Programming Control Abstractions Functions, function

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

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

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer Prelim 1 SOLUTION CS 2110, September 29, 2016, 7:30 PM 0 1 2 3 4 5 Total Question Name Loop invariants Recursion OO Short answer Exception handling Max 1 15 15 25 34 10 100 Score Grader 0. Name (1 point)

More information

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT Containers: Stack The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list. Also known as LIFO Last In, First Out) push insert an element

More information

Interfaces. An interface forms a contract between the object and the outside world.

Interfaces. An interface forms a contract between the object and the outside world. Interfaces An interface forms a contract between the object and the outside world. For example, the buttons on the television set are the interface between you and the electrical wiring on the other side

More information

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science Containers: Stack Jordi Cortadella and Jordi Petit Department of Computer Science The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list.

More information

Interfaces (1/2) An interface forms a contract between the object and the outside world.

Interfaces (1/2) An interface forms a contract between the object and the outside world. Interfaces (1/2) An interface forms a contract between the object and the outside world. For example, the buttons on remote controls for some machine. As you can see, an interface is a reference type,

More information