Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Invariants to Interfaces in Java

I've been thinking about creating a Java framework that would allow programmers to specify invariants (pre- and post-conditions) on interfaces. The purpose would be to make code more robust and reduce the number of unit tests that would need to be written for different implementations of the same interface.

I envisage creating some way of annotating methods with invariants that the programmer would also write. E.G.

interface Sort {
    int [] sort(int [] nums);
}

would be decorated with an annotation to ensure that any implementations return a sorted list. This annotation would be linked to a unit test that could be run at compile time against any implementation.

Is this a crazy idea or would this be useful to the wider programming community?

like image 497
Tarski Avatar asked Jul 22 '10 15:07

Tarski


3 Answers

This sounds like it could be related to JML and ESC/Java, both of which have found reasonably wide-spread adoption within the kinds of projects that need a little more software quality than is offered by the usual set of techniques.

like image 113
Gian Avatar answered Sep 19 '22 17:09

Gian


I think design by contract is a great idea and I've glanced at frameworks that provide that functionality in Java. I think what has held me back is that getting buy-in from a team for these sorts of frameworks can be difficult. I think it's perceived as being only of academic interest which is strange because really it's just like embedding unit tests within the code.

Java's main nod in this direction, the assert statement, has been around for several years but I rarely see it used - often only in the code I write myself! There's a lot of mileage in using asserts (especially combined with unit tests) and I've found a few bugs using them, it's just a pity people don't use them.

Cheers,

Ian.

like image 21
Ian Fairman Avatar answered Sep 20 '22 17:09

Ian Fairman


I think Bertrand Meyer's programming by contract idea is largely dead. He built pre- and post-conditions into Eiffel, but that language is below Latin on the usage scale.

There are Java programming by contract libraries out there; Contractor is one. But its day has come and gone. The fact is that even Eiffel had a way to turn them off in production, because the runtime cost wasn't worth the benefit.

Only 6 Eiffel questions on Stack Overflow - a small percentage indeed. If you search for SO tags with "contract" in them, you'll see a very small number. Not much interest in the topic on this site. It claims to draw the biggest audience of professional programmers in the world.

like image 23
duffymo Avatar answered Sep 21 '22 17:09

duffymo