Search code examples
javadesign-by-contractcontract

Design by Contract library (interface) thoughts?


I am looking at design by contract for a Java library, this what I came up with so far in terms of the interface.

The user could call executeContract and executeContract invokes invokeContract after calling 'require'. ensure is called after executeContract to ensure the correctness of what is returned by invokeContract.

This code also works as a callback method (anonymous inner class call).

What are your thoughts? Is this design by contract?, so far this helps me write testable Java code.

public interface IContractHandler {

    /**
     * Execute contract will invoke the #invokeContract method.  In the execute method, 
     * check for the validity of the preconditions and the post conditions.
     * 
     * The precondition can be null.
     * 
     * @param    precondInput -  Precondition Input Data, can be null.
     * @return                   Post condition output
     */
    public Object executeContract(final Object precondInput) throws ContractError;

    /**
     * Require that the preconditions are met.
     */
    public Object require(final Object precondInput) throws ContractError;

    /**
     * Ensure that the postconditions are met.
     */
    public Object ensure(final Object precondInput) throws ContractError;

    /**
     * The precondition can be null if the contract allows for that.
     * 
     * @param    precondInput -  Precondition Input Data, can be null.
     * @return                   Post condition output
     */
    public Object invokeContract(final Object precondInput) throws ContractError;

}

Solution

  • If you are looking for a generic solution to this I would recommend the Java Modelling Language. All of the pre/post-conditions (@requires/@ensures) can be specified in the annotations above the method you wish to check. It's my understanding that the JML compiler (jmlc) inserts runtime assertions into the bytecode.

    I believe ESC/Java2 has a similar type of functionallity but I've never used it before.