Reputation: 3436
I visited devday11 in the Netherlands last week and learned about Code Contract. I am thinking about implementing Code Contract, but the following is still unclear to me. How should I handle runtime code contract violations in my application?
For example I have a layer in my application that calls another layer with a null value. The function called had a Required Contact, so it throws a contract validation error. How should this be handled? So something like this
public string GetOrderSomething(OrderModel order)
{
Contract.Requires(order != null);
// jibidi jibeda do something
}
//other application layer
private void something()
{
Class.GetOrderSomething(null);
}
What should be done? Should I handle it with a normal try catch, should I not handle it at all? Is there something "special" I should do?
Upvotes: 2
Views: 190
Reputation: 273274
Assuming you already have an 'exception handling' policy in place, you should not have to do anything special.
If would be advisable to pick a specific exception:
public string GetOrderSomething(OrderModel order)
{
Contract.Requires<ArgumentNullException> (order != null, "order");
// jibidi jibeda do something
}
Now you can handle the ArgumentNullException in the same manner and place(s) as you would without (before) using contracts.
PS: Hope you liked the talk.
Upvotes: 1
Reputation: 7342
For this case you should do what you normally would do if there was
if (order == null) { throw new ArgumentNullException(); }
This CodeContract does not mean the class has been destabilized just that you passed a wrong parameter to the method...
However if this would be a Requires for some internal member and you know it should never be null, well that is another story. You would have a permanently unworkable class, and if you are unable to 'fix it' through catching, then probably some fatal exception should be raise and alerted.
Upvotes: 3
Reputation: 14755
In my opinion Codecontracts should be used to find programming errors at runtime.
Therefore codecontract-violation-execptions should be handled like avery other programming-error-exception (i.e. IndexOutOfBoundException)
Upvotes: 1