Code Contracts is a Microsoft open source project which allows you to express pre-conditions, post-conditions, and assertions directly in code.
Code Contracts is a Microsoft open source project, originating from Microsoft Research, which allows you to express pre-conditions, post-conditions, and assertions directly in code.
A check in a Code Contract is one that, if the code is correct, should always return true. In other words: it should not test whether the database is accessible or whether the user has entered an empty string -- those are outside factors. Code Contracts are there only to make sure your code is correct and maintains its invariants.
So, typically, you would do input parameter validation on public methods by explicitly checking the value and then throwing an exception if out of range. But for private methods -- which get called only by other code, and so can expect certain pre-conditions -- the input parameters can be checked with Code Contracts.
private void MyMethod(string machineId, int age)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(machineId));
Contract.Requires<ArgumentOutOfRangeException>(machineId.StartsWith("PEK"));
Contract.Requires<ArgumentOutOfRangeException>(age > 16);
//...
}
Post-conditions are expressions that must evaluate to true when the method is finished. A typical example is to verify that the output of a function is never null, or that it is within a certain range.
private string MachineNameOf(int id)
{
Contract.Requires<ArgumentOutOfRangeException>(id > 100);
Contract.Ensures(Contract.Result<string>() != null);
//...
}
GitHub: https://github.com/Microsoft/CodeContracts
Tools at: http://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970.
See also (historical): http://research.microsoft.com/en-us/projects/contracts.