Archive

Posts Tagged ‘Annotations’

.Net Contracts as Method Calls – Better Implementation and Adoption

Contracts in .Net are implemented as method calls (in the System.Diagnostics.Contracts namespace). This is in contrast to most of the other contracts-based tools that make use of other mechanisms to indicate contracts such as code comments in Java Modeling Language (JML), entity attributes or annotations in C4J, javadbc, and contract 1.4 Python (using annotations for function docstrings).

I think that representing contracts as method calls (in terms on an API) rather than annotations or comments is quite novel. Several advantages of using an API include :

Ease of extension– Constructs that can be used with attributes, annotations, and comments are limited and require a lot of effort in terms of parsing, extending compiler analyses including type checking and so on. IDE support is another facet with regard to the ease of extension; it is difficult to provide support for Intellisense when using attributes, annotations, and comments. IDE support is naturally available when authoring contracts as code.
Contract inheritance can be similarly supported out of the box, rather than by a separate treatment. (There would be another post on this).

Static contract checking of .Net contracts uses abstract interpretation (shown in less complicated way in this video. It’s pretty novel and to see how attributes-, annotations-, and comments- based contracts would fare in combination with abstract interpretation, I am going to make another post.)

Refactoring Support– Contracts as code become amenable to refactoring analyses like any other regular language entities. On the contrary, when having contracts as attributes, annotations, and comments, it is pretty difficult to adapt to refactorings and would require extension of parsing and compiler analyses.

Runtime Checking– To enforce contracts at runtime one has to include a binary rewriter in the build process when using attributes, annotations, and comments. Contracts as an API serve both as declarative contracts and as runtime-checked validation.

Extraction of Contracts– While attributes-, annotations-, and comments-based tools would need additional byte-code manipulation to extract contracts for contracts related tools this is included by default in the design of code contracts (Since compiling to MSIL (or any other intermediate language) is part of embedded contract languages design, see this paper.)

These positive points make code contracts much better than attributes-, annotations-, and comments- based contracts from implementation and adoption point of view.