Question

We are building business application not API for others to use, in this case, I prefer to use our validation logic in the if/then/throw model. I was told, it is better to use Code Contracts. I do not see any benefits, is there any obvious benefits that I am not seeing? I see problem using code contracts since it is static method call and also there is some code injection happens after the compile phase. Thanks

Was it helpful?

Solution

There are two obvious benefits:

(1) The code is much easier to read.

 Contract.Requires(someParam != null && someParam.SomeValue != 0);

versus

if (someParam != null && someParam.SomeValue != 0)
    throw new ArgumentNullException("someParam", someParam, "someParam can't be null and someParam.SomeValue can't be zero.");

Also, with Code Contracts, the predicate code is automatically put into the failure message so you don't need to write an explicit message like you do with normal exceptions.

(2) You can run Code Contracts static analysis on the code and it can find errors for you.

There are some less obvious benefits:

(3) You can generate documentation for the code contracts in the XML doc files.

(4) You can use Contract.Ensures() to express postconditional constraints. This allows you to avoid a lot of code like if (item.Property1 != null && item.Property1.Property2 != null) ... because you will know that neither Property or Property2 can be null.

(5) The code contracts form a block that is clearly separate from the rest of the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top