News

Google Takes 'Contract' Extensions for Java Open Source

Google recently open sourced its Contracts for Java (Cofoja) tool. Licensed under GNU LGPL, Cofoja adds a group of Java Boolean expressions inside annotations that are enabled via a JVM argument and checked at runtime to ensure that the code complies with a set of preconditions, postconditions and invariants -- or "honors" the contract.

The list of new annotations includes @Requires, @Ensures, @ThrowEnsures, and @Invariant, along with the Boolean expressions that specify the condition. Contracts are more persistent because they are inherited from interfaces and classes.

According to David Morgan, Andreas Leitner and Nhat Minh Le, who make up Google's Cofoja team, the new tool is based on Johnannes Rieken's Modern Jass. It was conceived and initially developed by two Google engineers within the company's famous "20 percent time," which frees employees to work on personal projects during work hours. It was later refined through an internship. 

The three developers said of Cofoja in their announcement on the company's Open Source blog: "Traditionally, Java programmers enforced preconditions using explicit parameter validation code in public methods, and assertions in non-public methods. Likewise, they enforced invariants and postconditions using assertions…. [But] new features in Java 5 have enabled a more convenient and expressive implementation of contracts."

The Design by Contract (DbC) technique was pioneered (and trademarked) by Goleta, Calif.-based software engineering firm Eiffel Software. The "contract" is a metaphor for a set of mutual "obligations" and "benefits" imposed on the various elements of a software system. According to Eiffel, this approach "guarantees that bugs will be prevented by a well-defined mechanism based on checks and balances."

Cofoja adds standard debugging information, such as source file and line numbers, to contract code. According to Google, debugging has been tested under JDB, Eclipse and IntelliJ. Currently, the Eclipse IDE "has issues" with setting breakpoints on contract annotations, but the source correspondence and step-by-step debugging works.

Using Cofoja requires developers to download one of the JAR files, which are currently unofficial (the Google developers promise to deliver official JARs "soon"); read the README file; add support for contracts to your project; and add contracts to your classes.

Google provides a simple example of a Java class annotated with a contract on the Cofoja project page.

About the Author

John K. Waters is the editor in chief of a number of Converge360.com sites, with a focus on high-end development, AI and future tech. He's been writing about cutting-edge technologies and culture of Silicon Valley for more than two decades, and he's written more than a dozen books. He also co-scripted the documentary film Silicon Valley: A 100 Year Renaissance, which aired on PBS.  He can be reached at [email protected].