I am working on a project (which includes JavaEE web apps and JavaSE apps) that has grown from a single developer to a team of three, and issues of readability and robustness are starting to emerge.
One glaring omission from the Java language has been fine tuned contracts, and how easily these are exposed to other developers. (By contracts I mean mostly validating method parameters and object pre/post conditions).
There are a few solutions that I am looking at, and I would like to get some feedback from others who have some practical experience.
It would seem that Java currently has two supported ways to define a contracts:
- The assert statement
- Throwing exceptions (such as IllegalArgumentException)
Asserts seem to only have value as a debugging tool. Since asserts are not enabled by default, the expectation is that developers will only rely on them during some formalized testing period, after which they are ignored.
Throwing exceptions seems like a robust option in that they allow almost any kind of checks to be made. However, the range of exceptions defined by the Java library seem to be poorly suited to defining contracts (for examply subclasses of IllegalArgumentException don't specifically with range issues, null checks etc, and subclasses of IllegalStateException appear to be concerned with network connection and file states), which forces each group to define their own range of exception classes.
But the biggest problem is that neither asserts nor exceptions explicitly map contract requirements to parameters or concepts like pre and post conditions. It is expected that the developer will manually maintain the JavaDoc comments with the code to make it clear under what conditions an assert will fail or an exception will be thrown.
It is clear to me that the standard Java libraries don't adequately support design by contract, which brings me to my questions:
Are my assumptions above correct, or have I missed some property of asserts and exceptions that actually makes them quite useful for this kind of problem?