{"id":438,"date":"2009-08-12T12:18:50","date_gmt":"2009-08-12T11:18:50","guid":{"rendered":"http:\/\/www.leading-edge-dev.de\/?p=438"},"modified":"2010-07-10T16:20:40","modified_gmt":"2010-07-10T15:20:40","slug":"code-contracts-relation-to-guard-classes","status":"publish","type":"post","link":"https:\/\/www.minddriven.de\/index.php\/technology\/dot-net\/code-contracts\/code-contracts-relation-to-guard-classes","title":{"rendered":"Code Contracts #7: Relation to Guard classes"},"content":{"rendered":"<p>Hey guys. After two months of many things to do I come back again with an article to Code Contracts. This day&#8217;s topic are guard classes and how they relate to Code Contracts.<\/p>\n<p>Recently my colleague AJ <a href=\"http:\/\/ajdotnet.wordpress.com\/2009\/08\/01\/posting-guards-guard-classes-explained\/\" target=\"_NEW\">posted<\/a> a really nice article about guard classes. He&#8217;s the first one who explained the topic as a whole and showed the advantages of using guards. In short version, guard classes in this context are mainly about guarding against passing invalid arguments into class methods.<\/p>\n<p>For example, without having a guard, you would check method arguments that way:<\/p>\n<pre class=\"brush:csharp\">public void FooMethod(string arg)\r\n{\r\n    if(arg == null)\r\n        throw new ArgumentNullException(\"arg\");\r\n    if(arg == \"\")\r\n        throw new ArgumentOutOfRangeException(\"arg\");\r\n    ...\r\n}<\/pre>\n<p>While this approach is defensive and can lead to less errors, it&#8217;s quite ugly to have those checks defined in every method directly. First, the if-clauses are polluting the method&#8217;s body. The <code>if<\/code> and <code>throw<\/code> keywords are too much information at this location. Second, for example if a string should not be empty, it&#8217;s obvious that it may not be null as well. And what if we want to log those exceptions or do something else (for example inform an administrator)? Here come guard classes into play. The aspect of throwing exceptions and perhaps do something before that is outsourced into a separate utility class <code>Guard<\/code>. With that on hand, the example from above would transform into:<\/p>\n<pre class=\"brush:csharp\">public void FooMethod(string arg)\r\n{\r\n    Guard.AssertNotEmpty(arg, \"arg\");\r\n    ...\r\n}<\/pre>\n<p>You can find the guard&#8217;s <code>AssertNotEmpty()<\/code> method in <a href=\"http:\/\/ajdotnet.wordpress.com\/2009\/08\/01\/posting-guards-guard-classes-explained\/\" target=\"_NEW\">AJ&#8217;s post<\/a>.<br \/>\nThe guard encapsulates the argument validation as cross-cutting-concern and makes it exchangable. The call clearly expresses what is done at that point and thus it&#8217;s better separated from the core logic of the method. It concentrated on the main purpose and not on the implementation details.<\/p>\n<p>Well, how are method guards fitting with Code Contracts or Design by Contract (DbC) at the whole? The simple answer: method guards are nearly equivalent to <b>preconditions<\/b> in DbC! They express the basic conditions on level of physical constraints, under which a method is expected to work correctly.<\/p>\n<p>With <b>Code Contracts<\/b>, in .NET 4.0 we don&#8217;t need an explicit <code>Guard<\/code> class any longer. The above example can be realized with Code Contracts as:<\/p>\n<pre class=\"brush:csharp\">public void FooMethod(string arg)\r\n{\r\n    Contract.Requires(arg != null, \"arg should not be null\");\r\n    Contract.Requires(arg != \"\", \"arg should not be empty\");\r\n    ...\r\n}<\/pre>\n<p>As with guard classes, this &#8218;precondition block&#8216; abstracts the implementation details of the check itself and it&#8217;s purpose is obvious, thus leading to a separation of the core logic, if you look at the method with developer&#8217;s eyes.<br \/>\nOne &#8218;problem&#8216; remains with this example. With the guard class we&#8217;ve had the chance to define individual methods, that fit our needs. For example, it checks for empty strings that they aren&#8217;t null as well (please take aside <code>String.IsNullOrEmpty()<\/code> for a moment) or it puts in logging logic. Code Contracts gives us just the <code>Contract.Requires()<\/code> method, which doesn&#8217;t have these abilities at first. If you have many repeating <em>individual checks<\/em> I suggest to use a separate static class that contains all of your needed checks as methods, that return a boolean value if the check passes. Those methods must be declared <b><code>[Pure]<\/code><\/b> in order to be used in contracts, thus they must be free of observable side effects. With such a class <code>Check<\/code>, the example above would look as follows:<\/p>\n<pre class=\"brush:csharp\">public void FooMethod(string arg)\r\n{\r\n    Contract.Requires(Check.NotEmpty(arg), \"arg should not be null or empty\");\r\n    ...\r\n}<\/pre>\n<p><code>Check<\/code> is simple in this case:<\/p>\n<pre class=\"brush:csharp\">public static class Check\r\n{\r\n    [Pure]\r\n    public static bool NotEmpty(string arg)\r\n    {\r\n        return ((arg != null) && (arg != \"\"));\r\n    }\r\n}<\/pre>\n<p>Alternatively, you could define <em>extension methods<\/em> on the datatypes, that should get individual checks. This frees you from a dedicated class, that must know all of the datatypes to check.<\/p>\n<p>For doing additional stuff like logging on fail of a precondition, you get the ability to plug in your own custom contract runtime class. Please read the <a href=\"http:\/\/msdn.microsoft.com\/devlabs\/dd491992.aspx\" target=\"_NEW\">Code Contracts documentation<\/a> for detailed information on this subject.<\/p>\n<p>Thus, Code Contracts give you the same advantages as guard classes. But moreover, there are clear additional benefits!<br \/>\n<b>First<\/b>, you are free to change the <em>check behavior<\/em> of your preconditions by configuration. The Code Contracts tools allow you to perform checks in debug mode only or even in the release build. Furthermore you can define, if you want the program to Assert or to throw an exception, if a precondition check fails and so on. Thus, you get a high flexibility to adapt Code Contracts to your own needs.<br \/>\n<b>Second<\/b>, Code Contracts give you the ability to directly <em>extend the interface<\/em> of your class. It allows you to define contracts on abstract classes and interfaces, that will be automatically taken into concrete implementations.<br \/>\n<b>Third<\/b>, contracts of all kinds are <em>derived<\/em> to every subclass of the class, where you have defined them. By that, you aren&#8217;t allowed to add any precondition in your subclass with Code Contracts, but you are able to define additional postconditions or invariants. Thereby, the compliance of the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Liskov_substitution_principle\" target=\"_NEW\"><em>Liskov Substitution Principle<\/em><\/a> is enforced on the level of contracts.<br \/>\n<b>Fourth<\/b>, don&#8217;t forget that DbC is a <em>design principle<\/em> and goes beyond the technical implementation on the level of guard classes.<br \/>\n<b>Fifth<\/b>, precondition checks allow <em>tool support<\/em>. They can be included in the run of the static checker and even the automatic test generator <a href=\"http:\/\/msdn.microsoft.com\/de-de\/devlabs\/cc950525.aspx\" target=\"_NEW\">Pex<\/a> is aware of contracts and uses preconditions of your methods as test oracle.<\/p>\n<p>That&#8217;s it for now. In conclusion, Code Contracts go beyond guard classes and because they are a core component of .NET 4.0, you don&#8217;t need custom guard classes any longer. Simply use contracts instead&#8230;<\/p>\n<p><a href=\"http:\/\/www.dotnetkicks.com\/kick\/?url=http%3a%2f%2fwww.leading-edge-dev.de%2f%3fp%3d438\"><img decoding=\"async\" src=\"http:\/\/www.dotnetkicks.com\/Services\/Images\/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.leading-edge-dev.de%2f%3fp%3d438\" border=\"0\" alt=\"kick it on DotNetKicks.com\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey guys. After two months of many things to do I come back again with an article to Code Contracts. This day&#8217;s topic are guard classes and how they relate to Code Contracts. Recently my colleague AJ posted a really nice article about guard classes. He&#8217;s the first one who explained the topic as a &hellip; <a href=\"https:\/\/www.minddriven.de\/index.php\/technology\/dot-net\/code-contracts\/code-contracts-relation-to-guard-classes\" class=\"more-link\"><span class=\"screen-reader-text\">Code Contracts #7: Relation to Guard classes<\/span> weiterlesen<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[126],"tags":[168,319,167,156],"class_list":["post-438","post","type-post","status-publish","format-standard","hentry","category-code-contracts","tag-net-4-0","tag-code-contracts","tag-guard-classes","tag-preconditions"],"_links":{"self":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/438","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/comments?post=438"}],"version-history":[{"count":7,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/438\/revisions"}],"predecessor-version":[{"id":954,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/438\/revisions\/954"}],"wp:attachment":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/media?parent=438"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/categories?post=438"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/tags?post=438"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}