c# - Is there a benefit in writing code contract instead of straight up check logic code? -


we building business application not api others use, in case, prefer use our validation logic in if/then/throw model. told, better use code contracts. not see benefits, there obvious benefits not seeing? see problem using code contracts since static method call , there code injection happens after compile phase. thanks

there 2 obvious benefits:

(1) code easier read.

 contract.requires(someparam != null && someparam.somevalue != 0); 

versus

if (someparam != null && someparam.somevalue != 0)     throw new argumentnullexception("someparam", someparam, "someparam can't null , someparam.somevalue can't zero."); 

also, code contracts, predicate code automatically put failure message don't need write explicit message normal exceptions.

(2) can run code contracts static analysis on code , can find errors you.

there less obvious benefits:

(3) can generate documentation code contracts in xml doc files.

(4) can use contract.ensures() express postconditional constraints. allows avoid lot of code if (item.property1 != null && item.property1.property2 != null) ... because know neither property or property2 can null.

(5) code contracts form block separate rest of code.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -