Search code examples
javadesign-by-contract

Java: Design by Contract annotations


I've recently started to read up on the Design by Contract design method but I don't understand some aspects of it. When using @pre etc, in a javadoc style comment, what purpose do these tags serve other than as documentation? Does the compiler use these for checks on the parameters before execution, or are these just indicators as to what kind of checks should occur in the method? e.g. if i have a getAge method;

/**
* @pre age >= 0 #CustomAgeException
*/
public int getAge() throws CustomAgeException{
    return age;
}

Will this cause a check at runtime before running the method, Does the compiler check this, or does this simply state to the developer that age must be equal or greater than 0 before calling this method, and that a check should be performed within getAge?


Solution

  • JavaDoc is inaccessible at runtime. The .class file doesn't contain them. (Reference see here StackOverflow question) Therefor, any code that would check for a javadoc is impossible.

    The comment is simply to make beautiful javadoc, or to keep the same pattern for these kind of notes across the classes. You'd have to implement the check yourself, or use a framework of some kind to actually perform the check. (Perhaps with real annotations on method/parameter level)

    Regards