Does Guava support Contract Classes, or otherwise allow interface documentation?

163 Views Asked by At

I was looking at Guava's Preconditions. It's great if you are using them in an implementation method, but is it possible to state interface contracts using them?

For example, in C# Contracts you can do this -

using System.Diagnostics.Contracts;

[ContractClass(typeof(FooContract))]
interface IFoo
{
    void Bar(int i);
}

[ContractClassFor(typeof(IFoo))]
abstract class FooContract : IFoo
{
    public void Bar(int i)
    {
        Contract.Requires(i >= 0);
    }
}

Is anything like this possible in Guava? If not, is there another java library for this?

1

There are 1 best solutions below

2
On BEST ANSWER

Design by Contract is a very elegant approach, but never caught on in Java. Early implementations used XDoclet, then annotations with AOP proxies, and later byte code preprocessing. The overhead of some implementations, their framework dependency, and being defined as metadata kept most developers from adopting the approach in practice. There are libraries, like Contracts For Java, but few are actively maintained.

Its more common to see explicit validation checks, such as Java's Objects.requireNonNull and Guava's Preconditions. JSR-303 Bean Validation is fairly common for data models but rarely used on interfaces. For interfaces its more popular to rely on unit tests and assistance by libraries, such as Guava's NullPointerTester, to ensure that the contract is being honored. A style choice that many prefer is to use JSR-305 for improved documentation that static analyzers like Findbugs and ErrorProne can validate. JSR-308 is similar, but has yet to catch on.