Replace guard clauses with code contracts

From The Library of Congress, via Flickr
.NET developers should consider replacing guard clauses with code contracts.
Guard Clauses
Kent Beck or Martin Fowler championed Guard Clauses. There aren’t many excuses to write functions with many levels in indentation.
void GetSalesTax()
{
if(_StateTaxRate == null || _CountyTaxRate == null)
return;
return (salesPrice * _StateTaxRate) + (salesPrice * _CountyTaxRate);
}
{
if(_StateTaxRate == null || _CountyTaxRate == null)
return;
return (salesPrice * _StateTaxRate) + (salesPrice * _CountyTaxRate);
}
Advantages
- placement makes it more obvious that these are preconditions (xUnit Patterns)
- “the guard clause says, ‘This is rare, and if it happens, do something and get out.’”, Martin Factor in Refactor
- avoids the arrow anti-pattern
Code Contracts
Microsoft Code Contracts provide a better alternative for software using .NET.
void GetSalesTax()
{
Contract.Requires(_StateTaxRate != null);
Contract.Requires(_CountyTaxRate != null);
return (salesPrice * _StateTaxRate) + (salesPrice * _CountyTaxRate));
}
{
Contract.Requires(_StateTaxRate != null);
Contract.Requires(_CountyTaxRate != null);
return (salesPrice * _StateTaxRate) + (salesPrice * _CountyTaxRate));
}
Advantages
- same benefits as guard clauses
- declarative
- can be statically verified
Tags: C#, Code Contracts, Refactor