Dustin's Pages

Saturday, February 19, 2011

Contracts for Java: Another Entrant in Java Programming by Contract

Earlier this month, the Open Source at Google blog featured a post on Contracts for Java, a project described in that post as a "new open source tool" that is "based on Modern Jass by Johannes Rieken." Design by ContractTM (DoC) is often associated with the Eiffel programming language and, in fact, this term is trademarked by Eiffel Software. Because the term "Design by Contract"TM is trademarked, other terms often used to describe the same approach include "Programming by Contract" and "Contract-First Development." (This might be an opportune moment to explicitly mention what my blog always states: trademarks used here remain the property of their respective owners.)

Java's directly available assertions mechanism can be used for similar purposes. The Preconditions, Postconditions, and Class Invariants section of Programming with Assertions states "While the assert construct is not a full-blown design-by-contract facility, it can help support an informal design-by-contract style of programming." This section then goes on to explain that assertions should not be used to "check the parameters of a public method," but that it is acceptable to check the parameters of nonpublic methods and that assertions can be used to check the postconditions of both public and nonpublic methods.

The reasoning for not using assertions for public method argument checking is that assertions can be turned off at runtime and thus cannot prevent improper invocation of the public methods. This continues to be an issue for Contracts for Java as well because it allows its runtime checking to be disabled. The Contracts for Java FAQ addresses the comparison of assertions to Contracts for Java in the answer to the question How is this better than using assert?

The comments (16 of them at time of this writing) on the Contracts for Java announcement are interesting. They indicate some general reservations among Java developers about the need for the project. The availability of existing frameworks (some of which I mentioned above), the availability of the standard assertion mechanism, and a desire to see support given to JSR-305 instead.

Contracts for Java is a very new project that is likely to have some growing pains. It enters an already crowded field and a possibly skeptical audience. It does have some things going for it including a general agreement about the wisdom in Design by ContractTM and Google support (via the 20% time piece of The Google Way). I will be interested to see if it can rise above the existing frameworks, libraries, and tools designed for contract-oriented Java development.