iContract: Design by Contract in Java - JavaWorld February
2001
Tutorial Details:
iContract: Design by Contract in Java
iContract: Design by Contract in Java
By: By Oliver Enseling
iContract allows you to explicitly specify your class contracts; no more guesswork as to what your classes promise
ouldn't it be nice if all Java classes that you use, including your own, lived up to their promises? In fact, wouldn't it be nice if you actually knew exactly what a given class promises? If you agree, read on -- Design by Contract and iContract come to the rescue.
Note: The code source for the examples in this article can be downloaded from Resources .
Design by Contract
The Design by Contract (DBC) software development technique ensures high-quality software by guaranteeing that every component of a system lives up to its expectations. As a developer using DBC, you specify component contracts as part of the component's interface. The contract specifies what that component expects of clients and what clients can expect of it.
Bertrand Meyer developed DBC as part of his Eiffel programming language. Regardless of its origin, DBC is a valuable design technique for all programming languages, including Java.
Central to DBC is the notion of an assertion -- a Boolean expression about the state of a software system. At runtime we evaluate the assertions at specific checkpoints during the system's execution. In a valid software system, all assertions evaluate to true. In other words, if any assertion evaluates to false, we consider the software system invalid or broken.
DBC's central notion somewhat relates to the #assert macro in C and C++ programming language. However DBC takes assertions a zillion levels further.
In DBC, we identify three different kinds of expressions:
Preconditions
Postconditions
Invariants
Let's examine each in more detail.
Preconditions
Preconditions specify conditions that must hold before a method can execute. As such, they are evaluated just before a method executes. Preconditions involve the system state and the arguments passed into the method.
Preconditions specify obligations that a client of a software component must meet before it may invoke a particular method of the component. If a precondition fails, a bug is in a software component's client.
Postconditions
In contrast, postconditions specify conditions that must hold after a method completes. Consequently, postconditions are executed after a method completes. Postconditions involve the old system state, the new system state, the method arguments, and the method's return value.
Postconditions specify guarantees that a software component makes to its clients. If a postcondition is violated, the software component has a bug.
Invariants
An invariant specifies a condition that must hold anytime a client could invoke an object's method. Invariants are defined as part of a class definition. In practice, invariants are evaluated anytime before and after a method on any class instance executes. A violation of an invariant may indicate a bug in either the client or the software component.
Assertions, inheritance, and interfaces
All assertions specified for a class and its methods apply to all subclasses as well. You can also specify assertions for interfaces. As such, all assertions of an interface must hold for all classes that implement the interface.
iContract -- DBC with Java
So far, we have talked about DBC in general. You probably have some idea by now what I am talking about, but if you are new to DBC, things might still be a bit foggy.
In this section, things will become more concrete. iContract, developed by Reto Kamer, adds constructs to Java that allow you to specify the DBC assertions we talked about earlier.
iContract basics
iContract is a preprocessor for Java. To use it, you first process your Java code with iContract, producing a set of decorated Java files. Then you compile the decorated Java code as usual with the Java compiler.
All iContract directives in Java code reside in class and method comments, just like Javadoc directives. In this way, iContract ensures complete backwards-compatibility with existing Java code, and you can always directly compile your Java code without the iContract assertions.
In a typical program lifecycle, you would move your system from a development environment into a test environment, then into a production environment. In the development environment, you would instrument your code with iContract assertions and run it. That way you can catch newly introduced bugs early on. In the test environment you may still want to keep the bulk of the assertions enabled, but you should take them out of performance-critical classes. Sometimes it even makes sense to keep some assertions enabled in a production environment, but only in classes that definitely are in no way critical to your system's performance. iContract allows you to explicitly select the classes that you want to instrument with assertions.
Preconditions
In iContract, you place preconditions in a method header using the @pre directive. Here's an example:
/**
* @pre f >= 0.0
*/
public float sqrt(float f) { ... }
The example precondition ensures that the argument f of function sqrt() is greater than or equal to zero. Clients who use that method are responsible for adhering to that precondition. If they don't, we as implementors of sqrt() are simply not responsible for the consequences.
The expression after the @pre is a Java Boolean expression.
Postconditions
Postconditions are likewise added to the header comment of the method they belong to. In iContract, the @post directive defines postconditions:
/**
* @pre f >= 0.0
* @post Math.abs((return * return) - f) < 0.001
*/
public float sqrt(float f) { ... }
In our example, we have added a postcondition that ensures that the sqrt() method calculates the square root of f within a specific margin of error (+/- 0.001).
iContract introduces some specific notations for postconditions. First of all, return stands for the return value of the method. At runtime, that will be replaced by the method's return value.
Within postconditions, there often exists a need to differentiate between the value of an argument before execution of the method and afterwards, supported in iContract with the @pre operator. If you append @pre to an expression in a postcondition, it will be evaluated based on the system state before the method executes:
/**
* Append an element to a collection.
*
* @post c.size() = c@pre.size() + 1
* @post c.contains(o)
*/
public void append(Collection c, Object o) { ... }
In the code above, the first postcondition specifies that the size of the collection must grow by 1 when we append an element. The expression c@pre refers to the collection c before execution of the append method.
Invariants
With iContract, you can specify invariants in the header comment of a class definition:
/**
* A PositiveInteger is an Integer that is guaranteed to be positive.
*
* @inv intValue() > 0
*/
class PositiveInteger extends Integer
{
...
}
In this example, the invariant guarantees that the PositiveInteger 's value is always greater than or equal to zero. That assertion is checked before and after execution of any method of that class.
Object Constraint Language (OCL)
Although the assertion expressions in iContract are valid Java expressions, they are modeled after a subset of the Object Constraints Language (OCL). OCL is one of the standards maintained and coordinated by the Object Management Group, or OMG. (OMG takes care of CORBA and related stuff, in case you miss the connection.) OCL was intended to specify constraints within object modeling tools that support the Unified Modeling Language (UML), another standard guarded by OMG.
Because the iContract expressions language is modeled after OCL, it provides some advanced logical operators beyond Java's own logic operators.
Quantifiers: forall and exists
iContract supports forall and exists quantifiers. The forall quantifier specifies that a condition should hold true for every element in a collection:
/*
* @invariant forall IEmployee e in getEmployees() |
*
getRooms().contains(e.getOffice())
*/
The above invariant specifies that every employee returned by getEmployees() has an office in the collection of rooms returned by getRooms() . Except for the forall keyword, the syntax is the same as that of an exists expression.
Here is an example using exists :
/**
* @post exists IRoom r in getRooms() | r.isAvailable()
*/
That postcondition specifies that after the associated method executes, the collection returned by getRooms() will contain at least one available room. The exists proceeds the Java type of the collection element -- IRoom in the example. r is a variable that refers to any element in the collection. The in keyword is followed by an expression that returns a collection ( Enumeration , Array , or Collection ). That expression is followed by a vertical bar, followed by a condition involving the element variable, r in the example. Employ the exists quantifier when a condition must hold true for at least one element in a collection.
Both forall and exists can be applied to different kinds of Java collections. They support Enumeration s, Array s, and Collection s.
Implications: implies
iContract provides the implies operator to specify constraints of the form, "If A holds, then B must hold as well." We say, "A implies B." Example:
/**
* @invariant getRooms().isEmpty() implies getEmployees().isEmpty() // no rooms, no employees
*/
That invariant expresses that when the getRooms() collection is empty, the getEmployees() collection must be empty as well. Note that it does not specify that when getEmployees() is empty, getRooms() must be empty as well.
You can also combine the logical operators just introduced to form complex assertions. Example:
/**
* @invariant forall IEmployee e1 in getEmployees() |
*
forall IEmployee e2 in getEmployees() |
*
(e1 != e2
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: iContract: Design by Contract in Java - JavaWorld February
2001
View Tutorial: iContract: Design by Contract in Java - JavaWorld February
2001
Related
Tutorials:
|
Displaying 1 - 50 of about 3008 Related Tutorials.
|
Design By Contract
Java: Design By Contract
Java: Design By Contract
Bertrand Meyer formalized a programming
methodology called Design by Contract, which has become
popular in some groups |
Definition of Bioinformatics
;
About Bioinformatics
In February 2001, the human genome was finally... for Biotechnology Information (NCBI
2001) defines bioinformatics as:
" |
GJTester - Java Unit Testing Tool
tool, accomplishes the
unit, regression and contract testing of your Java...
In case of upgrading JAVA VM checking the product is
still functioning
Contract...
GJTester - Java Unit Testing Tool
GJTester - Java |
JFreeChart - An Introduction
java chart library.
David Gilbert founded the JFreeChart project in February 2000 |
Open Source Jobs
of Linux / Open Source professionals, providing both contract and direct hire... Schedulers in Java
On some projects, you find you need to execute certain jobs... will see how Java developers can implement such a requirement using |
Open Source Jobs
of Linux / Open Source professionals, providing both contract and direct hire... Schedulers in Java
On some projects, you find you need to execute certain jobs... will see how Java developers can implement such a requirement using |
Open Source Jobs
of Linux / Open Source professionals, providing both contract and direct hire... Schedulers in Java
On some projects, you find you need to execute certain jobs... will see how Java developers can implement such a requirement using |
Java Releases
Java 1_5_0_01
February
2005
Java 2 Platform,
Standard Edition 1.4 (J2SE 1.4)
February
2002
Java 2 Platform... (JDK 1.1)
February
1997
Java Development Kit
1.0 (JDK |
New to Java?
New to Java - New to java tutorial
New to Java...;
If you are
new to Java
technology and you want to learn Java and make career in the Java technology then this page is for you. Here we have |
New to Java?
New to Java - New to java tutorial
New to Java...;
If you are
new to Java
technology and you want to learn Java and make career in the Java technology then this page is for you. Here we have |
JAVA JAZZ UP - Free online Java magazine
Free Java Magazine,Free Java Magazines,JAVA JAZZ UP Issue 1,Free Online Java Magazine
JAVA JAZZ UP Issue 1,Free online Java magazine
JAVA JAZZ UP - Free online Java
magazine
JAVA JAZZ UP - Free online Java |
Java Get Month
Java Get Month
Java Get Month...;
In the previous Java examples, we have discussed about date functions... the
current month of the existing year. This Java get month example is simply |
Java util package Examples
Java Util,Java Util List,Java Util Example,Java Util Program List - Online Java Tutorials
Java Util Examples List - Util...;
The util package or java provides many utility interfaces |
Java Notes: Table of Contents
Cohesion
Design By Contract
Process - Iterative...
Java Programming Notes
Java Notes: Table of Contents
Java Notes. These Java programming notes are written to fill in missing |
Chart & Graphs Tutorials in Java
Chart & Graphs Tutorials in Java
Chart & Graphs Tutorials in Java
 ... of Graphs and Charts Tutorials in Java. Our Chart and Graphs
tutorials will help learn |
Java Util Examples List
Java Util,Java Util List,Java Util Example,Java Util Program List - Online Java Tutorials
Java Util Examples List - Util...;
The util package or java provides many utility interfaces |
Open Source Java Database
Open Source Java Database
Open Source Java Database
An Open Source Java Database
One$DB is an Open Source version of Daffodil DB, our commercial Java Database. One$DB is a standards based (JDBC 3.0 and SQL |
Java Interview Questions - Page 12
by contract?
Answer: The design by contract specifies the
obligations... the use of design by
contract, especially in the case of checked exceptions...
Java Interview Questions,interview questions java |
Determining If a Year is a Leap Year in Java
Determining Leap Year in Java,How to Determine If a Year is a Leap Year or not in Java
Determining If a Year is a Leap Year in Java
  |
Java get number of Days in Month
Java get number of Days in Month
Java get number of Days in Month
 ... a Calendar
object. Here we are going to get the number of days in the month February |
Java Date Example
Java Date Examples
Java Date Examples... 19
Capricorn
January 20 - February 18
Aquarius
February 19 - March 20
Pisces
March 21 - April 19
Aries |
Bayanihan Linux 4 Beta 1 has been released
and Technology Institute last October 2001. This was the first initiative... by February 2.
After three BETA version and a release candidate, the final version of Bayanihan Linux 3 was finally launched last February 24, 2004 during |
Java: Strengths
Java: Strengths
Java: Strengths
Java is an excellent programming language. For most programming...
The top reason Java has become popular
is because |
JEE 5 API
.
Java Authorization Contract for Containers
The Java Authorization Contract for Containers (Java ACC) specification (JSR-115) defines new... the APIs available on the Java EE 5 platform.
API |
Java Tools
Java Tools
Java Tools
 ...;
Java Compiler
To commence with Java programming, we must know the
significance of Java |
Java Interpreter
Java Interpreter
Java Interpreter... can run Java on most platforms provided a platform
must has a Java interpreter. That is why Java applications are platform
independent. Java interpreter |
Java Tools
Java Tools
Java Tools
 ...;
Java Compiler
To commence with Java programming, we must know the
significance of Java |
Java Interpreter
Java Interpreter
Java Interpreter... can run Java on most platforms provided a platform
must has a Java interpreter. That is why Java applications are platform
independent. Java interpreter |
Java Compiler
Java Compiler,Java Compiler Example
Java Compiler...;
To commence with Java programming, we must know the
significance of Java Compiler. When we write any program in a text editor like
Notepad, we use |
Java - Threads in Java
Java Thread Example Code - Threads in Java
Java - Threads in Java
 ... including Java. Threads allow the
program to perform multiple tasks |
Java Compiler
Java Compiler,Java Compiler Example
Java Compiler...;
To commence with Java programming, we must know the
significance of Java Compiler. When we write any program in a text editor like
Notepad, we use |
Java Compiler
Java Compiler,Java Compiler Example
Java Compiler...;
To commence with Java programming, we must know the
significance of Java Compiler. When we write any program in a text editor like
Notepad, we use |
Java: Java Tutorials
Java Free Tutorials ? Java Beginners Tutorials,Free Online Java Tutorials,Free Sun Java Tutorials
Java: Java Tutorials...
Java
Java is perhaps the most important language of our time. Joe Grip's |
Java review
Java Review
Java review
Organized by Java: How to Program chapter.
About Java - history...-Oriented Programming
Graphical User Interface Components I
Typical Java |
Java Debugger
Java Compiler,Java Compiler Example
Java Debugger...;
Java debugger helps in finding and the fixing of bugs
in Java language programs. The Java debugger is denoted as jdb. It works
like a command-line |
Java Help and Java Glossary
Java Help,Java Programming Help,Sun Java Help,Online Java Help
Java Help and Java Glossary
 ...;
We provide Java |
Java Debugger
Java Debugger,Java Debuggers
Java Debugger...;
Java debugger helps in finding and the fixing of bugs
in Java language programs. The Java debugger is denoted as jdb. It works
like a command-line |
Java Debugger
Java Compiler,Java Compiler Example
Java Debugger...;
Java debugger helps in finding and the fixing of bugs
in Java language programs. The Java debugger is denoted as jdb. It works
like a command |
Java API
Java API, what is java api?
Java API...;
Java API
Java API is not but a set of classes and interfaces that comes with the JDK. Java API is actually a huge |
Java: Weaknesses
Java: Weaknesses
Java: Weaknesses
Altho Java is arguably the best overall programming languages...
Elliotte Rusty Harold, author of several good Java books |
Java Virtual Machine
Java: Java Virtual Machine
Java: Java Virtual Machine
After you read this section, you should be able to understand
how it's possible for a Java applet/application to run on many |
File I/O - Text Files
Java: File I/O - Text Files
Java NotesFile I/O - Text Files
Java can read several types of information from files: binary,
Java objects, text, zipped files, etc. One of the most |
Java 5.0
Java 5,JDK 5,Java 5 Tutorials,Java 5 Tutorial,Sun Java 5.0 Online Tutorials
Java 5.0
 ...;
Java 5.0 tutorials |
Java Interpreter
We can run Java on most platforms provided a platform must has a Java
interpreter
Java Interpreter
 ...;
We can run Java |
Java - Continue statement in Java
Continue Statement in Java,Java Continue Statement,Java Continue Statement Example
Java - Continue statement in Java...
such as C, C++, java etc. Sometimes we do not need to execute some statements
under |
Java I/0 Examples
Java I/O,Java Input Output,Java IO Stream,Java IO Package,Java IO Example
Java I/0 Examples
 ...;
What is Java I/O?
The Java I/O means Java Input/Output |
Java Thread
Java thread
Java Thread
 ...;
A java... flow of control
within a program. Programmer may use java thread mechanism |
Java as a general purpose language
Java as a general purpose language
Java as a general...;
Java is an Object oriented application programming
language developed by Sun Microsystems. Java is a very powerful general |
Java Software
Java Software
Java Software
You need sofware to develop your Java programs.
You can use the software in the UMUC computer labs, but most students
install Java software |
Package categories in Java
Package categories in Java
Package categories in Java
 ...;
Java supports two types of packages as shown below |
|
|
|