{"id":717,"date":"2012-01-17T18:46:15","date_gmt":"2012-01-18T00:46:15","guid":{"rendered":"https:\/\/daedtech.wpenginepowered.com\/?p=717"},"modified":"2015-06-30T03:18:31","modified_gmt":"2015-06-30T08:18:31","slug":"poor-mans-code-contracts","status":"publish","type":"post","link":"https:\/\/daedtech.com\/poor-mans-code-contracts\/","title":{"rendered":"Poor Man&#8217;s Code Contracts"},"content":{"rendered":"<h3>What&#8217;s Wrong with Code Contracts?!?<\/h3>\n<p>Let me start out by saying that I really see nothing wrong with code contracts, and what I&#8217;m offering is not intended as any kind of replacement for them in the slightest.  Rather, I&#8217;m offering a solution for a situation where contracts are not available to you.  This might occur for any number of reasons:<\/p>\n<ol>\n<li>You don&#8217;t know how to use them and don&#8217;t have time to learn.<\/li>\n<li>You&#8217;re working on a legacy code base and aren&#8217;t able to retrofit wholesale or gradually.<\/li>\n<li>You don&#8217;t have approval to use them in a project to which you&#8217;re contributing.<\/li>\n<\/ol>\n<p>Let&#8217;s just assume that one of these, or some other consideration I hadn&#8217;t thought of is true.<\/p>\n<h3>The Problem<\/h3>\n<p>If you&#8217;re coding defensively and diligent about enforcing preconditions, you probably have a lot of code like this:<\/p>\n<pre lang=\"C#\">\r\npublic void DoSomething(Foo foo, Bar, bar)\r\n{\r\n  if(foo == null)\r\n  {\r\n    throw new ArgumentNullException(\"foo\");\r\n  }\r\n  if(bar == null)\r\n  {\r\n    throw new ArgumentException(\"bar\");\r\n  }\r\n\r\n  \/\/Finally, get down to business...\r\n}\r\n<\/pre>\n<p>With code contracts, you can compact that guard code and make things more readable:<\/p>\n<pre lang=\"C#\">\r\npublic void DoSomething(Foo foo, Bar, bar)\r\n{\r\n  Contract.Requires(foo != null);\r\n  Contract.Requires(bar != null);\r\n\r\n  \/\/Finally, get down to business...\r\n}\r\n<\/pre>\n<p>I won&#8217;t go into much more detail here &#8212; I&#8217;ve <a href=\"https:\/\/daedtech.com\/microsoft-code-contracts\">blogged about code contracts<\/a> in the past.  <\/p>\n<p>But, if you don&#8217;t have access to code contracts, you can achieve the same thing, with even more concise syntax.<\/p>\n<pre lang=\"C#\">\r\npublic void DoSomething(Foo foo, Bar, bar)\r\n{\r\n  _Validator.VerifyParamsNonNull(foo, bar);\r\n\r\n  \/\/Finally, get down to business...\r\n}\r\n<\/pre>\n<h3>The Mechanism<\/h3>\n<p>This is actually pretty simple in concept, but it&#8217;s something that I&#8217;ve found myself using routinely.  Here is an example of what the &#8220;Validator&#8221; class looks like in one of my code bases:<\/p>\n<pre lang=\"C#\">\r\n    public class InvariantValidator : IInvariantValidator\r\n    {\r\n        \/\/\/ <summary>Verify a (reference) method parameter as non-null<\/summary>\r\n        \/\/\/ <param name=\"argument\">The parameter in question<\/param>\r\n        \/\/\/ <param name=\"message\">Optional message to go along with the thrown exception<\/param>\r\n        public virtual void VerifyNonNull<T>(T argument, string message = \"Invalid Argument\") where T : class\r\n        {\r\n            if (argument == null)\r\n            {\r\n                throw new ArgumentNullException(\"argument\", message);\r\n            }\r\n        }\r\n\r\n        \/\/\/ <summary>Verify a parameters list of objects<\/summary>\r\n        \/\/\/ <param name=\"arguments\"><\/param>\r\n        public virtual void VerifyParamsNonNull(params object[] arguments)\r\n        {\r\n            VerifyNonNull(arguments);\r\n\r\n            foreach (object myParameter in arguments)\r\n            {\r\n                VerifyNonNull(myParameter);\r\n            }\r\n        }\r\n\r\n        \/\/\/ <summary>Verify that a string is not null or empty<\/summary>\r\n        \/\/\/ <param name=\"target\">String to check<\/param>\r\n        \/\/\/ <param name=\"message\">Optional parameter for exception message<\/param>\r\n        public virtual void VerifyNotNullOrEmpty(string target, string message = \"String cannot be null or empty.\")\r\n        {\r\n            if (string.IsNullOrEmpty(target))\r\n            {\r\n                throw new InvalidOperationException(message);\r\n            }\r\n        }\r\n    }\r\n<\/pre>\n<p>Pretty simple, huh?  So simple that you might consider not bothering, except&#8230;<\/p>\n<p>Except that for me, personally, anything that saves lines of code, repeat typing, and <a href=\"http:\/\/en.wikipedia.org\/wiki\/Cyclomatic_complexity\">cyclomatic complexity<\/a> is good.  I&#8217;m very meticulous about that.  Think of every place in your code base that you have an if(foo == null) throw paradigm, and add one to a cyclomatic complexity calculator.  This is order O(n) on the number of methods in your code base.  Contrast that to 1 in this code base.  Not O(1), but actually 1.<\/p>\n<p>I also find that this makes my methods substantially more readable at a glance, partitioning the method effectively into guard code and what you actually want to do.  The vast majority of the time, you don&#8217;t care about the guard code, and don&#8217;t really have to think about it in this case.  It doesn&#8217;t occupy your thought briefly as you figure out where the actual guts of the method are.  You&#8217;re used to seeing a precondition\/invariant one-liner at the start of a method, and you immediately skip it unless it&#8217;s the source of your issue, in which case you inspect it.<\/p>\n<p>I find that streamlined contexting to be valuable.  There&#8217;s a clear place for the guard code and a clear place for the business logic, and I&#8217;m used to seeing them separated.<\/p>\n<h3>Cross-Cutting Concerns<\/h3>\n<p>Everything I said above is true of Code Contracts as well as my knock off.  Some time back, I did some <a href=\"https:\/\/daedtech.com\/pubs\/NoException.pdf\">research on Code Contracts<\/a> and during the course of that project, we devised a way to have Code Contracts behave differently in debug mode (throwing exceptions) than in release mode (supplying sensible defaults).  This was part of an experimental effort to wrap simple C# classes and create versions that <a href=\"http:\/\/en.wikipedia.org\/wiki\/Exception_guarantees\">the &#8220;no throw guarantee&#8221;<\/a>.<\/p>\n<p>But, Code Contracts work with explicit static method calls.  With this interface validator, I can use an IoC container define run-time configurable, cross cutting behavior on precondition\/invariant violations.  That creates a powerful paradigm where, in some cases, I can throw exceptions, in other cases, I can log and throw, or in still other cases, I can do something crazy like pop up message boxes.  The particulars don&#8217;t matter so much as the ability to plug in a behavior at configuration time and have it cross-cut throughout the application.  (Note, this is only possible if you make your Validator an injectable dependency).<\/p>\n<h3>Final Thoughts<\/h3>\n<p>So, I thought that was worth sharing.  It&#8217;s simple &#8212; perhaps so simple as to be obvious &#8212; but I&#8217;ve gotten a lot of mileage out of it in scenarios where I couldn&#8217;t use contracts, and sometimes I find myself even preferring it.  There&#8217;s no learning curve, so other people don&#8217;t look at it and say things like &#8220;where do I download Code Contracts&#8221; or &#8220;what does this attribute mean?&#8221;  And, it&#8217;s easy to fully customize.  Of course, this does nothing about enforcing instance level invariants, and to get the rich experience of code contracts, you&#8217;d at the very least need to define some kind of method that accepted a delegate type for evaluation, but this is, again, not intended to replace contracts.<\/p>\n<p>Just another tool for your arsenal, if you want it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What&#8217;s Wrong with Code Contracts?!? Let me start out by saying that I really see nothing wrong with code contracts, and what I&#8217;m offering is not intended as any kind of replacement for them in the slightest. Rather, I&#8217;m offering a solution for a situation where contracts are not available to you. This might occur&#8230;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"_kad_post_classname":"","footnotes":""},"categories":[67],"tags":[10,22],"class_list":["post-717","post","type-post","status-publish","format-standard","hentry","category-net","tag-c","tag-code-contracts"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Poor Man&#039;s Code Contracts - DaedTech<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/daedtech.com\/poor-mans-code-contracts\/\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:title\" content=\"Poor Man&#039;s Code Contracts - DaedTech\" \/>\n<meta name=\"twitter:description\" content=\"What&#8217;s Wrong with Code Contracts?!? Let me start out by saying that I really see nothing wrong with code contracts, and what I&#8217;m offering is not intended as any kind of replacement for them in the slightest. Rather, I&#8217;m offering a solution for a situation where contracts are not available to you. This might occur...\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Erik Dietrich\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/\"},\"author\":{\"name\":\"Erik Dietrich\",\"@id\":\"https:\\\/\\\/daedtech.com\\\/#\\\/schema\\\/person\\\/3dae63e91a0fa60c8051a2171fa687d2\"},\"headline\":\"Poor Man&#8217;s Code Contracts\",\"datePublished\":\"2012-01-18T00:46:15+00:00\",\"dateModified\":\"2015-06-30T08:18:31+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/\"},\"wordCount\":794,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\\\/\\\/daedtech.com\\\/#organization\"},\"keywords\":[\"C#\",\"Code Contracts\"],\"articleSection\":[\".NET\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/\",\"url\":\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/\",\"name\":\"Poor Man's Code Contracts - DaedTech\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/daedtech.com\\\/#website\"},\"datePublished\":\"2012-01-18T00:46:15+00:00\",\"dateModified\":\"2015-06-30T08:18:31+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/daedtech.com\\\/poor-mans-code-contracts\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/daedtech.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Poor Man&#8217;s Code Contracts\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/daedtech.com\\\/#website\",\"url\":\"https:\\\/\\\/daedtech.com\\\/\",\"name\":\"DaedTech\",\"description\":\"Stories about Software\",\"publisher\":{\"@id\":\"https:\\\/\\\/daedtech.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/daedtech.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/daedtech.com\\\/#organization\",\"name\":\"DaedTech LLC\",\"url\":\"https:\\\/\\\/daedtech.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/daedtech.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/daedtech.com\\\/wp-content\\\/uploads\\\/2015\\\/07\\\/SmallLogo.jpg\",\"contentUrl\":\"https:\\\/\\\/daedtech.com\\\/wp-content\\\/uploads\\\/2015\\\/07\\\/SmallLogo.jpg\",\"width\":82,\"height\":84,\"caption\":\"DaedTech LLC\"},\"image\":{\"@id\":\"https:\\\/\\\/daedtech.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/daedtech.com\\\/#\\\/schema\\\/person\\\/3dae63e91a0fa60c8051a2171fa687d2\",\"name\":\"Erik Dietrich\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/691ca004bd18f464e9467b2f838e8fbc7a9a2c9eb8568b04a834ac653f3ab1d7?s=96&d=wavatar&r=pg\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/691ca004bd18f464e9467b2f838e8fbc7a9a2c9eb8568b04a834ac653f3ab1d7?s=96&d=wavatar&r=pg\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/691ca004bd18f464e9467b2f838e8fbc7a9a2c9eb8568b04a834ac653f3ab1d7?s=96&d=wavatar&r=pg\",\"caption\":\"Erik Dietrich\"},\"sameAs\":[\"https:\\\/\\\/daedtech.com\"],\"url\":\"https:\\\/\\\/daedtech.com\\\/author\\\/erik\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Poor Man's Code Contracts - DaedTech","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/daedtech.com\/poor-mans-code-contracts\/","twitter_card":"summary_large_image","twitter_title":"Poor Man's Code Contracts - DaedTech","twitter_description":"What&#8217;s Wrong with Code Contracts?!? Let me start out by saying that I really see nothing wrong with code contracts, and what I&#8217;m offering is not intended as any kind of replacement for them in the slightest. Rather, I&#8217;m offering a solution for a situation where contracts are not available to you. This might occur...","twitter_misc":{"Written by":"Erik Dietrich","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/daedtech.com\/poor-mans-code-contracts\/#article","isPartOf":{"@id":"https:\/\/daedtech.com\/poor-mans-code-contracts\/"},"author":{"name":"Erik Dietrich","@id":"https:\/\/daedtech.com\/#\/schema\/person\/3dae63e91a0fa60c8051a2171fa687d2"},"headline":"Poor Man&#8217;s Code Contracts","datePublished":"2012-01-18T00:46:15+00:00","dateModified":"2015-06-30T08:18:31+00:00","mainEntityOfPage":{"@id":"https:\/\/daedtech.com\/poor-mans-code-contracts\/"},"wordCount":794,"commentCount":2,"publisher":{"@id":"https:\/\/daedtech.com\/#organization"},"keywords":["C#","Code Contracts"],"articleSection":[".NET"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/daedtech.com\/poor-mans-code-contracts\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/daedtech.com\/poor-mans-code-contracts\/","url":"https:\/\/daedtech.com\/poor-mans-code-contracts\/","name":"Poor Man's Code Contracts - DaedTech","isPartOf":{"@id":"https:\/\/daedtech.com\/#website"},"datePublished":"2012-01-18T00:46:15+00:00","dateModified":"2015-06-30T08:18:31+00:00","breadcrumb":{"@id":"https:\/\/daedtech.com\/poor-mans-code-contracts\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/daedtech.com\/poor-mans-code-contracts\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/daedtech.com\/poor-mans-code-contracts\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/daedtech.com\/"},{"@type":"ListItem","position":2,"name":"Poor Man&#8217;s Code Contracts"}]},{"@type":"WebSite","@id":"https:\/\/daedtech.com\/#website","url":"https:\/\/daedtech.com\/","name":"DaedTech","description":"Stories about Software","publisher":{"@id":"https:\/\/daedtech.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/daedtech.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/daedtech.com\/#organization","name":"DaedTech LLC","url":"https:\/\/daedtech.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/daedtech.com\/#\/schema\/logo\/image\/","url":"https:\/\/daedtech.com\/wp-content\/uploads\/2015\/07\/SmallLogo.jpg","contentUrl":"https:\/\/daedtech.com\/wp-content\/uploads\/2015\/07\/SmallLogo.jpg","width":82,"height":84,"caption":"DaedTech LLC"},"image":{"@id":"https:\/\/daedtech.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/daedtech.com\/#\/schema\/person\/3dae63e91a0fa60c8051a2171fa687d2","name":"Erik Dietrich","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/691ca004bd18f464e9467b2f838e8fbc7a9a2c9eb8568b04a834ac653f3ab1d7?s=96&d=wavatar&r=pg","url":"https:\/\/secure.gravatar.com\/avatar\/691ca004bd18f464e9467b2f838e8fbc7a9a2c9eb8568b04a834ac653f3ab1d7?s=96&d=wavatar&r=pg","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/691ca004bd18f464e9467b2f838e8fbc7a9a2c9eb8568b04a834ac653f3ab1d7?s=96&d=wavatar&r=pg","caption":"Erik Dietrich"},"sameAs":["https:\/\/daedtech.com"],"url":"https:\/\/daedtech.com\/author\/erik\/"}]}},"_links":{"self":[{"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/posts\/717","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/comments?post=717"}],"version-history":[{"count":0,"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/posts\/717\/revisions"}],"wp:attachment":[{"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/media?parent=717"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/categories?post=717"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/daedtech.com\/wp-json\/wp\/v2\/tags?post=717"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}