Design By Contract is a fancy way of describing a really nice way of embedding logic within objects that ensure certain, necessary conditions are met within a method before (or after) underlying logic is called. The embedded logic is the "contract" that is enforced whenever the method is called. And it's far more effective than just commenting the code and hoping that callers use it the correct way. The term Design By Contract was coined by Dr. Betrand Meyer with the creation of the Eiffel language, but the concept is language-agnostic to be sure.
Preconditions checks determine if the caller obeyed the rules and postcondition checks determine if the method behaved properly. I must admit that we use the precondition logic far more at this point.
There are lots of articles on the web describing Design By Contract, but I always like Billy McCafferty's posts so here's the link to his:
http://devlicio.us/blogs/billy_mccafferty/archive/2006/09/22/design_2d00_by_2d00_contract_3a00_-a-practical-introduction.aspx.
We use this technique alot within our business objects. Besides basic data checks ("is the CustomerID > 0"), it's also effective for more business-specific checks ("does this user have permission to update this customer?"). From a code structure/methodology point of view, it is a great way to help enforce separation of business logic within the business object from the outer layers of the application (web pages, web services, Windows services, for instance).
For the life of me I can't find the original site where we grabbed our Design By Contract class library from (I think it came from a link at the end of Billy McCafferty's post that is now inactive), but here is another one that will likely do just fine:
http://www.codeproject.com/KB/cs/designbycontract.aspx.
In the case of the library we use, when implementing a Design By Contract precondition into one of our business object methods, we simply add a line like this to the code:
Check.Require(customerId > 0, "Invalid CustomerID!!")
In our case, if the contract condition (the first parameter) fails, a DesignByContractException is thrown (with the second parameter serving as the exception's message), which is caught as needed by the calling method and handled as required.
One can also use a postcondition check with Check.Ensure. This would indicate a failure in the method itself as opposed to a failure in the way that the method was called.
And when we get to .Net 4.0, we'll check out System.Diagnostics.Contracts namespace. Looks like it will be built in and even easier to use.
After all, we strive to create bug-free software and Design By Contract techniques help us push toward that goal.
Give Design By Contract a try! You'll be hooked quickly....