Cofoja

Short version

Get sample code from  Cofoja. Then run 'gradle rundemo'.


Description

Cofoja is a not very recent contract library for Java. I haven’t used in on an actual project, but I came across it while researching the Programming by Contract chapter, so I gave it a go. To be honest, I struggled a little while trying to set it up. Not that it’s hard, but I found some online documentation rather contradicting or obsolete and I got confused. Anyway, after some tinkering, I’ve come up with the following Gradle build file:

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    runtime 'org.ow2.asm:asm-all:5.1'
}

project.ext {
    cofoja = "lib/cofoja-1.3-20160207.jar"
}

compileJava {
    classpath = files "${project.cofoja}"
}

task runDemo(type: JavaExec) {
    classpath = sourceSets.main.runtimeClasspath
    main = "cofoja.Time"
    jvmArgs = ["-javaagent:${project.cofoja}"]
}

Here are some things that might not be very obvious:

  • There are no recent versions of Cofoja in the common online repos, which is why I’ve included a recent version in the example and hard-coded the path.
  •  When compiling the code with the Cofoja jar in the classpath, you’ll get two files: Time.class and Time.contract. The second one is the result of Cofoja’s annotation processing. Some online documentation will tell you to specify '-processor com.google.java.contract.core.apt.AnnotationProcessor' during compilation. This instruction can be ignored, since the jar already contains a file called services/javax.annotation.processing.Processor, which sets up the processor.
  • The magic happens when Cofoja is used to instrument the code at runtime (-javaagent). If you omit this JVM argument, no contracts will be enforced.