What's Happening

Design by Contract with Eclipse

Aug 14th, 2008 by blog | 0

Developing code should involve a robust and rigorous testing step. Unit testing is commonly used but there is a different more flexible way introduced by Bertrand Meyer called “Design by Contract” (wikipedia), where the server ensures that the invoked stated is correct if the client provides correct data. Whether the “contract” is fulfilled by both parties can be tested by assert statements in the code, however this may cause a log of clutter. A nicer way is to write the tests in the “documentation” part. Several packages provide such an environment for Java. Here I looked at Contract4J.

If you know how, it is real easy to set up your “design by contract” environment in Eclipse. The following step-by-step instruction is for Eclipse 3.2 and Java 5.0.

1) Download AspectJ

in eclipse go to Help->Software Updates->Find and Install->Search for new Features to Install->Add remote location…
here you have to add the URL for the AspectJ version matching your Eclipse version – search for the URL here:
Continue to install AspectJ by following the wizard prompts.

2) Download Contract4J

in the archive should be Contract4J.jar and lib/*.jar

3) Get an AspectJ Project

Create a new *AspectJ* Project by doing
File -> New -> Others.. -> AspectJProject

Convert a Java project to an AspectJ project in eclipseor

Convert your current project to an AspectJ project by right clicking on the project and -> Convert to AspectJ Project

4) Link in depended libraries

At project properties :
1) Add Contract4J.jar to AspectJ Aspect Path Libraries (or AspectJ Build InPath in Eclipse 3.4)
2) Add Contract4J.jar to the Build Path
3) Add other dependent libraries (from the lib/ folder in the zip) to the build Path

5) Write code

E.g. a counter.

Where the member variable is tested to have a range between 1 and 4.

6) Execute Program

Run as -> AspectJ / Java Application

The output for e.g. the counter should be like this:

Current count 1
Current count 2
Current count 3
Current count 4
[FATAL] DefaultContractEnforcer: *** Contract Failure (Counter.java:22): Invar test “count>=0 && count <5″ for “Counter” failed. Count must be between 0 and 5 [failure cause = null]

Which indicates that the counter is outside the valid range and therefore that the contract is violated.

Leave a Reply