Design by Contract is a methodology that was populated by Eiffel language. The DbC ideas have common aims with Test Driven Development (TDD). Both focus on software quality and tests written with code in parallel.
The idea of DbC is based on contract - contract between client code and service. Each class is a service that provides set of methods (nothing new). Each method call is a client. Contract between them says that if the client satisfies some preconditions then service will ensure some postconditions. That's all. The contracts (or assertions) should be declared easily with the method as there may be lots of them. C# does not support such assertions easily. Some people do it in this way:
public decimal AccountBalance
{
[Ensures("result > 0")]
get;
[Requires("value > 0", "Balance must be greater than zero")]
[Ensures("AccountBalance == value")]
set;
}
The Requires attribute represents precondition assertion and the Ensures attribute checks postconditions. The notation is not perfect here but it shows how the assertions (tests) are embedded within code. Let's ignore some performance implications of the methodology and think how it simplifies test-centric development.
Unfortunatelly there is no good implementation of the methodology in .NET yet. There is a research project in Microsoft that tries to introduce such language (Spec#) to the .NET platform. Sample assertions in the Spec# looks like this:
public class ArrayList
{
public void Insert(int index, object value)
requires 0 <= index && index < Count
requires !IsReadOnly otherwise NotSupportedException
{
...
}
}
As you can see the difference is in syntax only, not in idea of the methodology. So Microsoft goes this way.
I believe the DbC is a powerful mechanism that can save you tears (as many other test-centric mechanisms). I hope the Spec# will become commonly used C# extension (I only played with it yet). Finally: everyone intrested in TDD methodologies should carrefully overview the DbC techniques.