Benefits of Code Contracts

Why should I use code contracts like

Contract.Requires<ArgumentNullException>( x != null, "x" ); 

instead of the old old

 if (x!=null){} else throw... 

Are there any other advantages besides brevity?

+7
optimization c #
source share
2 answers

According to MSDN :

The benefits of code contracts are as follows:

  • Improved testing: code contracts provide static contract verification, verification of compliance and documentation.
  • Automated Testing Tools. You can use code contracts to create more meaningful unit tests by filtering out meaningless test arguments that don't satisfy the prerequisites.
  • Static check: the static controller can decide if there are any contract violations without running the program. It checks for implicit contracts, such as null dereferences and array boundaries, and explicit contracts.
  • Reference documentation: The documentation generator complements existing XML documentation files with contract information. There are also style sheets that you can use with Sandcastle so that the generated documentation pages contain sections of contracts.

Your mileage may vary, which of these points is important or not. I found the third and fourth (static checking and documentation) particularly interesting.

In other words, this is a more structured way to describe contracts (instead of constructs like if (x!=null){} ) that other tools can understand.

+10
source share

Besides syntactic sugar, Code Contracts is Microsoft's tool for the Design by Contract paradigm. http://en.wikipedia.org/wiki/Design_by_contract

Basically, this is a great way of thinking when you design your classes and operations. From experience, DbC works great with Test Driven Development, in which you basically define contracts and record tests for this before writing any business logic.

Behind the scenes, the contract contract generates code similar to your good old code at compile time, so the IL code contains all the checks.

For example, class

 public class Scheduler { public bool ScheduleTask(string taskname, DateTime startTime, DateTime endTime) { Contract.Requires(!string.IsNullOrWhiteSpace(taskname)); Contract.Requires(startTime != null); Contract.Requires(endTime != null); return true; } } 

The result is something like

 public bool ScheduleTask(string taskname, DateTime startTime, DateTime endTime) { __ContractsRuntime.Requires(!string.IsNullOrWhiteSpace(taskname), null, "!string.IsNullOrWhiteSpace(taskname)"); __ContractsRuntime.Requires(true, null, "startTime != null"); __ContractsRuntime.Requires(true, null, "endTime != null"); return true; } 

where _ContractsRuntime.Requests is as follows

 internal static void Requires(bool condition, string msg, string conditionTxt) { if (!condition) { __ContractsRuntime.ReportFailure(ContractFailureKind.Precondition, msg, conditionTxt, null); } } 
+5
source share

All Articles