<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Stefano Ricciardi &#187; design</title>
	<atom:link href="http://stefanoricciardi.com/tag/design/feed/" rel="self" type="application/rss+xml" />
	<link>http://stefanoricciardi.com</link>
	<description>On Software Development and Thereabouts</description>
	<lastBuildDate>Thu, 02 Sep 2010 15:01:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>The Difference Between Encapsulation and Information Hiding</title>
		<link>http://stefanoricciardi.com/2009/12/06/encapsulation-and-information-hiding/</link>
		<comments>http://stefanoricciardi.com/2009/12/06/encapsulation-and-information-hiding/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 21:01:24 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=264</guid>
		<description><![CDATA[If you ask people familiar with Object Oriented Design which are the most important concepts of the paradigm to them, you will surely hear things like classes, inheritance, polymorphism. Some may talk about genericity; somebody may even mention encapsulation or information hiding. In fact, many designers use the words encapsulation and information hiding interchangeably. Encapsulation [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F12%2F06%2Fencapsulation-and-information-hiding%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F12%2F06%2Fencapsulation-and-information-hiding%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p><a title="Locks by Leo Reynolds, on Flickr" href="http://www.flickr.com/photos/lwr/863297155/"><img style="float:left;margin-right:20px;" src="http://farm2.static.flickr.com/1004/863297155_17b9031799_m.jpg" alt="Locks" width="240" height="240" /></a>If you ask people familiar with Object Oriented Design which are the most important concepts of the paradigm to them, you will surely hear things like <em>classes</em>, <em>inheritance</em>, <em>polymorphism</em>. Some may talk about <em>genericity</em>; somebody may even mention <em>encapsulation</em> or <em>information hiding</em>.</p>
<p>In fact, many designers use the words encapsulation and information hiding interchangeably.</p>
<h3>Encapsulation</h3>
<p>In his book  <a href="http://www.amazon.com/Fundamentals-Object-Oriented-Design-Meilir-Page-Jones/dp/020169946X/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1260132242&amp;sr=8-1-spell">Fundamental Of Object Oriented Design in UML</a> Meilir Page-Jones gives the following definition for encapsulation:</p>
<blockquote><p><strong>Encapsulation</strong> is the grouping of related ideas into one unit, which can thereafter be referred to by a single name.</p></blockquote>
<p><em>Single name</em> is here the key word to get an insight of what encapsulation is about: a subroutine (or <em>function</em> as we call it nowadays), for example, is a name that refers to a unit of code. Something  that instead of being repeated over and over in the source code is factored out in a single place.</p>
<p>As such the function is the simplest level of encapsulation and abstraction: a designer can refer to it by name as a single entity and even forget the details of the internals and only remember its interface.</p>
<p>Encapsulation in the object oriented world expands on this concept from the subroutine level to the object level: attributes that represents the state of an object and the methods that work on them are packaged into an object type.</p>
<h3>Information Hiding</h3>
<p>The concept of <strong>information hiding</strong> is very similar and was first introduced by Parnas in his seminal paper &#8220;<a title="http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf" rel="nofollow" href="http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf">On the Criteria to Be Used in Decomposing Systems Into Modules&#8221;</a> (pdf) almost 40 years ago.</p>
<p>Parnas used the term discussing about which criteria lead to good <em>modularity </em>in <em>structured programming</em>:</p>
<blockquote><p>every module in the [...] decomposition is characterized by its knowledge of a design decision which it hides from all others. Its interface or definition was chosen to reveal as little as possible about its inner workings.</p></blockquote>
<p>As you see, here also we talk about some separate entity or module which has some responsibility that we need fulfilled, and we are not interested about <em>how </em>it is fulfilled. But the emphasis here is a bit more about <em>hiding</em> the details from other modules (or objects in the OO world).</p>
<p>Information hiding gives the designer the freedom to <em>modify </em>how the responsibility is fulfilled by a module/object. This is especially valuable at points where the design (or even the requirements) are likely to change.</p>
<h3>Uncle Bob Helps Explaining the Difference</h3>
<p>Maybe one of the best example explaining the difference between encapsulation and information hiding can be found in Uncle Bob&#8217;s most recent book <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1260132316&amp;sr=1-1">Clean Code</a> (even though the author was not talking about these 2 concepts explicitely).</p>
<p>The following type is merely encapsulated: we have created a concept representing a geometrical concept (the point in a 2D space).</p>
<pre class="brush:csharp">
public class Point
{
    public double x;
    public double y;
}
</pre>
<p>The following type, on the other hand, is an example of information hiding applied to the same concept:</p>
<pre class="brush:csharp">
public interface Point
{
    double GetX();
    double GetY();
    void SetCartesian(double x, double y);
    double GetR();
    double GetTheta();
    void SetPolar(double r, double theta);
}
</pre>
<p>In this second example, the actual implementation is completely <em>hidden</em>: the client doesn&#8217;t know whether the internal representation of the point is in rectangular or polar coordinates.</p>
<p>If you are curious and want to know more, you can refer to the following <a href="http://c2.com/cgi/wiki?EncapsulationIsNotInformationHiding">wiki</a> for more opinions on the differences (or lack thereof) between encapsulation and information hiding.</p>
<p><em>Photo by <a href="http://www.flickr.com/people/lwr/">Leo Reynolds</a></em>.<br />
<!-- Kick It --><br />
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.net%2f2009%2f12%2f06%2fencapsulation-and-information-hiding%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.net%2f2009%2f12%2f06%2fencapsulation-and-information-hiding%2f" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<!-- Kick It end --><br />
<a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://stefanoricciardi.net/2009/12/06/encapsulation-and-information-hiding/"><br />
        <img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://stefanoricciardi.net/2009/12/06/encapsulation-and-information-hiding/"><br />
    </a><br />
<!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0 none;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/12/06/encapsulation-and-information-hiding/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Book Review: The Pragmatic Programmer</title>
		<link>http://stefanoricciardi.com/2009/11/09/book-review-the-pragmatic-programmer/</link>
		<comments>http://stefanoricciardi.com/2009/11/09/book-review-the-pragmatic-programmer/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 11:05:26 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Reviews]]></category>
		<category><![CDATA[book]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[review]]></category>
		<category><![CDATA[software craftsmanship]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.wordpress.com/?p=530</guid>
		<description><![CDATA[I recently embarked on a journey to read (or re-read) all the great classic books in the software literature. The Pragmatic Programmer is one of those books which is usually included in the recommended readings for a software developer, and deservedly so. The book, released in 1999, has been so successful that the two authors, [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F11%2F09%2Fbook-review-the-pragmatic-programmer%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F11%2F09%2Fbook-review-the-pragmatic-programmer%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<h1><a title="The Pragmatic Programmer" href="http://www.amazon.co.uk/Pragmatic-Programmer-Andrew-Hunt/dp/020161622X/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1256673093&amp;sr=8-1"><img style="display:inline;border-width:0;margin:0 5px 0 0;" title="thepragrmaticprogrammer" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2009/10/thepragrmaticprogrammer.jpg" border="0" alt="The Pragmatic Programmer" width="244" height="244" align="left" /></a></h1>
<p>I recently embarked on a journey to read (or re-read) all the great classic books in the software literature.</p>
<p>The <a title="The Pragmatic Programmer" href="http://www.amazon.co.uk/Pragmatic-Programmer-Andrew-Hunt/dp/020161622X/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1256673093&amp;sr=8-1">Pragmatic Programmer</a> is one of those books which is usually included in the recommended readings for a software developer, and deservedly so. The book, released in 1999, has been so successful that the two authors, <a href="http://pragprog.com/about">Andrew Hunt</a> and <a href="http://pragprog.com/about">David Thomas</a>, have since created their own publishing company, the <a href="http://pragprog.com/">Pragmatic Bookshelf</a> (with titles spanning a broad range of programming topics).</p>
<p>This book must really  have been a breakthrough when it hit the bookstores about 10 years ago. 1999 is one year before Kent Beck released his seminal book <a href="http://www.amazon.co.uk/Extreme-Programming-Explained-Embrace-Change/dp/0321278658/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1257536953&amp;sr=8-1"><em>Extreme Programming Explained: Embrace Change</em></a><em> </em>which exposed the agile software process to the masses<strong>.</strong> Both Andrew Hunt and David Thomas originally signed the <a href="http://agilemanifesto.org/">Agile Manifesto</a>, together with Kent Beck himself and a few others, and it shows. But it would be dismissive to describe this as a book on agile since it’s much more.</p>
<p>The book is structured as a series short 46 sections. Each section has challenges and even exercises where appropriate. It touches on <strong>design</strong> concepts such as orthogonality, decoupling, <a href="http://en.wikipedia.org/wiki/DRY">DRY</a> (which it coined), <a href="http://en.wikipedia.org/wiki/Domain_Specific_Languages">Domain Specific Languages</a>, <a href="http://en.wikipedia.org/wiki/Design_By_Contract">Design By Contract</a>, <a href="http://en.wikipedia.org/wiki/Metaprogramming">Metaprogramming</a>, <a href="http://en.wikipedia.org/wiki/Refactoring">Refactoring</a>; it has pages on <strong>process</strong> topics like build automation, “design to test”, test automation, estimation, requirements collection.</p>
<p>But where the book really shines is where it shows you how to “<em>become a better programmer</em>” (today we might say a <em>software</em> <em>craftsman</em>) and to take pride from it.</p>
<p>The <strong>pragmatic programmer</strong> is an early adopter, is inquisitive and realistic, and tries to be &#8220;f<em>amiliar with a broad range of technologies and environments</em>&#8220;.</p>
<p>The pragmatic programmer takes responsibility, values quality but recognizes when the software is “<em>good enough</em>”. The pragmatic programmer is a continuous learner (the “<em>learn at least one new language every year</em>” advice is often quoted), thinks critically about what he reads and hear, and knows how to communicate. The books explains how you can build these qualities.</p>
<p>The sections that I enjoyed the most is when the authors discuss about <em>tools</em>: the pragmatic programmer prefers working with plain text (the book itself it’s been written from XML transformed into TeX), masters a shell (command line) which he/she can program, knows at least one text manipulation language (e.g. Perl) and how to generate code from metadata.</p>
<p>Even though the recent reprints have links to later tools like JUnit, Ant, etc… still a few parts of the book begin to show its age. For example the authors suggest to pick <em>one</em> text editor (e.g. Emacs or VI) and become a power user (not just know the keyboard shortcuts but also how to extend it to suit your needs). There used to be a time when you could spend your whole working day inside Emacs: you could edit and build your programs, open a shell, handle emails and browse newsgroups, edit text documents (with LaTeX for example), even play games. As much as I love Emacs, I believe today it’s virtually impossible to beat the productivity gains you can get with specialized IDEs like Visual Studio or Eclipse, with their intellisense and plug-in ecosystems.</p>
<p>All in all, the Pragmatic Programmer is easily one of the best book on software development I have ever read. It has really inspired me to continue my journey to become a <em>“better programmer”</em>. Thanks to this book, I have now in my action list: learn a scripting language (Ruby?); learn a functional language (F#?); learn how to use a shell in the Windows environment (PowerShell?); read a book on usability; read a book on the human side of software development (“Peopleware&#8221;?). A lot of things. A lot of fun ahead.</p>
<p><!-- Kick it BEGIN --><br />
<a href="http://www.dotnetkicks.com/kick/?url=http%3A%2F%2Fstefanoricciardi.net%2F2009%2F11%2F09%2Fbook-review-th%E2%80%A6tic-programmer%2F"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3A%2F%2Fstefanoricciardi.net%2F2009%2F11%2F09%2Fbook-review-th%E2%80%A6tic-programmer%2F" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<!-- Kick it END --></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Book-Review-The-Pragmatic-Programmer"><img src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.net%2F2009%2F11%2F09%2Fbook-review-the-pragmatic-programmer%2F" alt="Shout it" /></a></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0 none;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/review">Review</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/11/09/book-review-the-pragmatic-programmer/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Making WCF Serializer Work with Circular References</title>
		<link>http://stefanoricciardi.com/2009/10/22/making-wcf-serializer-work-with-circular-references/</link>
		<comments>http://stefanoricciardi.com/2009/10/22/making-wcf-serializer-work-with-circular-references/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 12:07:43 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[WCF]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=465</guid>
		<description><![CDATA[The Problem of Circular References Recently I had to model a tree-like structure using a variation of the GoF composite design pattern and to pass this class to a WCF service for further processing. The class has circular reference as described by the following drawing: Therefore off I went to naively create my DataContract along [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F22%2Fmaking-wcf-serializer-work-with-circular-references%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F22%2Fmaking-wcf-serializer-work-with-circular-references%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<h1>The Problem of Circular References</h1>
<p>Recently I had to model a tree-like structure using a variation of the GoF <a title="Composite Design Pattern" href="http://en.wikipedia.org/wiki/Composite_pattern">composite design pattern</a> and to pass this class to a WCF service for further processing.</p>
<p>The class has circular reference as described by the following drawing:</p>
<p><img class="aligncenter size-full wp-image-474" title="Example of a Node Recursion" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2009/10/noderecursion.gif" alt="Example of a Node Recursion" width="219" height="117" /></p>
<p>Therefore off I went to naively create my <strong>DataContract</strong> along the following lines:</p>
<pre class="brush:csharp">
[DataContract(Namespace = "http://schemas.acme.it/2009/10"]
public class Node
{
	[DataMember(Name="Children", Order=2)]
    private IList&lt;Node&gt; children;

    [DataMember(Name="Id", Order=0)]
    public string Id { get; set; }

    [DataMember(Name="Parent", Order=1)]
    public Node Parent { get; set; }

    public Node()
    {
        children = new List&lt;Node&gt;()
    }

    public void AddChild(Node node)
    {
        this.children.Add(node);
        node.Parent = this;
    }

    public IList&lt;Node&gt; Children
    {
        get
        {
            IList&lt;Node&gt; result = new List(this.children);
            foreach (Node child in this.children)
            {
                foreach (Node innerChild in child.Children)
                {
                result.Add(innerChild);
                }
            }

            return result;
        }
    }
}
</pre>
<p>Unfortunately at run time I was greeted by the following exception:<br />
<code>Object graph for type 'System.Collections.Generic.List`1[[Node ...]]' contains cycles and cannot be serialized if reference tracking is disabled.</code>.</p>
<h1>The Solution</h1>
<p>Reading around I realized that up until some time ago you had to implement your own <strong>DataContractSerializer</strong> (see for example this <a href="http://blogs.msdn.com/sowmy/archive/2006/03/26/561188.aspx">post </a> by Sowmy Srinivasan).</p>
<p>Luckily, it turns out that with NET 3.5 SP1 everything is much simpler: you just have to use the <strong>IsReference</strong> parameter in the <strong>DataContract</strong> attribute, as follows:</p>
<pre class="brush:csharp">
[DataContract(Namespace = "http://schemas.acme.it/2009/10", IsReference=true)]
public class Node
{
    // everything same as in the example above.
}
</pre>
<h1>The Catch</h1>
<p>For some reason, if you turn on the <strong>IsReference</strong> attribute, then you <em>cannot </em>set the <strong>IsRequired</strong> attribute to <code>true</code> on <em>any</em> <strong>DataMember</strong> of the DataContract. The reason is somehow explained <a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/e5d38e14-31b0-4991-a988-d578c564e92d">here</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F22%2Fmaking-wcf-serializer-work-with-circular-references"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<!-- Kick it END --></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://stefanoricciardi.com/2009/10/22/making-wcf-serializer-work-with-circular-references/"><br />
<img src="http://dotnetshoutout.com/image.axd?url=http://stefanoricciardi.com/2009/10/22/making-wcf-serializer-work-with-circular-references/" alt="Shout it" /><br />
</a></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border: 0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display: inline; float: none; margin: 0; padding: 0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/wcf">WCF</a>, <a rel="tag" href="http://technorati.com/tags/soa">SOA</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/22/making-wcf-serializer-work-with-circular-references/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Service Locator Pattern in C# with Lazy Initialization</title>
		<link>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/</link>
		<comments>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 12:37:35 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=423</guid>
		<description><![CDATA[In my previous post Service Locator Pattern in C#: A Simple Example I introduced a fairly basic implementation of this pattern. In this post I will address one of the limitations of that implementation, introducing a form of lazy initialization. Defining Lazy Initialization Lazy initialization improves the performance of object creation, deferring long running initializations [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F13%2Fservice-locator-pattern-in-c-with-lazy-initialization%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F13%2Fservice-locator-pattern-in-c-with-lazy-initialization%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In my previous post <a href="http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/">Service Locator Pattern in C#: A Simple Example</a> I introduced a fairly basic implementation of this pattern. In this post I will address one of the limitations of that implementation, introducing a form of <strong>lazy initialization</strong>.</p>
<h3>Defining Lazy Initialization</h3>
<p>Lazy initialization improves the performance of object creation, deferring long running initializations until they are really needed.</p>
<p>Suppose for example that some of the fields of an object need to be read from the database. If a client never access those fields, accessing the database to retrieve those fields has been useless and it has just made object initialization slower (often by a considerable factor).</p>
<p>Martin Fowler credits Kent Beck with the introduction of the lazy initialization pattern, and in <a href="http://www.amazon.co.uk/Enterprise-Application-Architecture-Addison-Wesley-signature/dp/0321127420">PoEAA </a>book he describes it in the following way:</p>
<blockquote><p>The basic idea is that every access to the field checks to see if it&#8217;s null. If so, it calculates the value of the field before returning the field. To make this work you have to ensure that the field is self-encapsulated, meaning that all access to the field, even from within the class, is done through a getting method.</p></blockquote>
<p>Fairly simple.</p>
<h3>The Improved Service Locator</h3>
<p>The following is the improved version of the service locator which uses lazy initialization of the services.</p>
<pre class="brush:csharp">
internal class ServiceLocator : IServiceLocator
{
    // a map between contracts -&gt; concrete implementation classes
    private IDictionary&lt;Type, Type&gt; servicesType;

    // a map containing references to concrete implementation already instantiated
    // (the service locator uses lazy instantiation).
    private IDictionary&lt;Type, object&gt; instantiatedServices;

    internal ServiceLocator()
    {
        this.servicesType = new Dictionary&lt;Type, Type&gt;();
        this.instantiatedServices = new Dictionary&lt;Type, object&gt;();

        this.BuildServiceTypesMap();
    }

    public T GetService&lt;T&gt;()
    {
        if (this.instantiatedServices.ContainsKey(typeof(T)))
        {
            return (T)this.instantiatedServices[typeof(T)];
        }
        else
        {
            // lazy initialization
            try
            {
                // use reflection to invoke the service
                ConstructorInfo constructor = servicesType[typeof(T)].GetConstructor(new Type[0]);
                Debug.Assert(constructor != null, &quot;Cannot find a suitable constructor for &quot; + typeof(T));

                T service = (T)constructor.Invoke(null);

                // add the service to the ones that we have already instantiated
                instantiatedServices.Add(typeof(T), service);

                return service;
            }
            catch (KeyNotFoundException)
            {
                throw new ApplicationException&quot;The requested service is not registered&quot;);
            }
        }
    }

    private void BuildServiceTypesMap()
    {
        servicesType.Add(typeof(IServiceA),
            typeof(ServiceA));

        servicesType.Add(typeof(IServiceB),
            typeof(ServiceB));

        servicesType.Add(typeof(IServiceC),
            typeof(ServiceC));
     }
}
</pre>
<p>We are now maintaining two separate maps:</p>
<ul>
<li><code>servicesType</code> maps an interface describing a service to a <em>type</em> T that implements that interface.</li>
<li><code>instantiatedServices</code> maps an interface to an <em>instantiated</em> object of class T.</li>
</ul>
<p>Both maps are initialized in the constructor. However only the first map is filled. Every time <code>GetService</code> is invoked, we check whether a concrete implementation of that service has already been created. If not, we create that service implementation retrieving its constructor via reflection, and we put a reference to that implementation in the <code>instantiatedServices</code> map.</p>
<p>For this to work, the service implementation needs to expose a default (parameterless) constructor.</p>
<p>If services creation time is significant, lazy initialization can save you quite some time during application start up, with very little cost in terms of increased complexity.</p>
<p><i>Next article in the series: <a href="http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/">A Singleton Service Locator</a></i></p>
<p>
<!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div></p>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Service Locator Pattern in C#: A Simple Example</title>
		<link>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/</link>
		<comments>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 12:24:31 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=366</guid>
		<description><![CDATA[A Service Locator is a common design pattern that allows decoupling clients of services (described by a public interface) from the concrete class implementing those services. Martin Fowler has a great introduction on the topic in his Inversion of Control Containers and the Dependency Injection pattern. What follows is a very simple service locator implementation [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F09%2F25%2Fservice-locator-pattern-in-csharpa-simple-example%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F09%2F25%2Fservice-locator-pattern-in-csharpa-simple-example%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>A Service Locator is a common design pattern that allows decoupling clients of services (described by a public interface) from the concrete class implementing those services. Martin Fowler has a great introduction on the topic in his <a href="http://www.martinfowler.com/articles/injection.html">Inversion of Control Containers and the Dependency Injection pattern</a>.</p>
<p>What follows is a very simple service locator implementation in C# based on generics.</p>
<p>Let&#8217;s start defining the contract of a service locator.</p>
<pre class="brush:csharp">
public interface IServiceLocator
{
    T GetService&lt;T&gt;();
}
</pre>
<p>Now let&#8217;s see a very simple implementation of this contract:</p>
<pre class="brush:csharp">
class ServiceLocator : IServiceLocator
{
	// map that contains pairs of interfaces and
	// references to concrete implementations
	private IDictionary&lt;object, object&gt; services;

	internal ServiceLocator()
	{
		services = new Dictionary&lt;object, object&gt;();

		// fill the map
		this.services.Add(typeof(IServiceA), new ServiceA());
		this.services.Add(typeof(IServiceB), new ServiceB());
		this.services.Add(typeof(IServiceC), new ServiceC());
	}

	public T GetService&lt;T&gt;()
	{
		try
		{
			return (T)services[typeof(T)];
		}
		catch (KeyNotFoundException)
		{
			throw new ApplicationException(&quot;The requested service is not registered&quot;);
		}
	}
}
</pre>
<p>As you can see,</p>
<ul>
<li>the constructor of the class registers all the available services in a dictionary. In our example, we have 3 different services accessible through <code>IServiceA</code>, <code>IServiceB</code>, and <code>IServiceC</code>. It is assumed here that <code>ServiceA</code> implements <code>IServiceA</code> and so forth.</li>
<li>the generic GetService() method returns a reference the correct implementation fetching it from the dictionary</li>
</ul>
<p>This is how a client would invoke the service:</p>
<pre class="brush:csharp">
IServiceLocator locator = new ServiceLocator();
IServiceA myServiceA = locator.GetService&lt;IServiceA&gt;();
</pre>
<p>The clients do not know the actual classes implementing the service. They only have to interact with the service locator to get to an implementation.</p>
<h3>Improvements</h3>
<p>This is as simple as it gets. There are several improvements that a real-world implementation of a service locator should consider (what follows is only a partial list):</p>
<ul>
<li>The service locator itself might be a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a>. There usually is no need to have two instances of a service locator.</li>
<li><a href="http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/">Lazy initialization</a> of services might be considered. In the example above, the constructor creates new instances for all possible services; initialization might be deferred until some client actually requests a particular service.</li>
<li>The mapping between interfaces and implementation might be more flexible using metadata (e.g. through application configuration files)</li>
</ul>
<p><em>Next article in the series: <a href="http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/">Service Locator Pattern in C# with Lazy Initialization</a></em></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Code Contracts and Inheritance</title>
		<link>http://stefanoricciardi.com/2009/07/17/code-contracts-and-inheritance/</link>
		<comments>http://stefanoricciardi.com/2009/07/17/code-contracts-and-inheritance/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 22:10:00 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.wordpress.com/?p=223</guid>
		<description><![CDATA[The Liskov Substitution Principle This is the third post on a mini-series about Microsoft Code Contracts and why you should use it to write more robust and reusable code. After introducing pre and post-conditions and invariants, it’s now time to discuss one of the most powerful concepts of the Design by Contract, that is contracts [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F07%2F17%2Fcode-contracts-and-inheritance%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F07%2F17%2Fcode-contracts-and-inheritance%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<h3>The Liskov Substitution Principle</h3>
<p>This is the third post on a mini-series about Microsoft Code Contracts and why you should use it to write more robust and reusable code.</p>
<p>After introducing <a href="http://stefanoricciardi.com/2009/06/26/introduction-to-microsoft-code-contracts-with-visual-studio-2008/">pre and post-conditions</a> and <a href="http://stefanoricciardi.com/2009/07/01/code-contracts-invariants/">invariants</a>, it’s now time to discuss one of the most powerful concepts of the Design by Contract, that is <em>contracts inheritance</em>. The importance of the interactions between contracts and inheritance is described in one of the cornerstone concepts of Object Oriented Programming, that goes under the name of the <strong>Liskov Substitution Principle:</strong></p>
<blockquote><p>If for each object o1 of type S there is an object o2 of type T such that for all programs P  defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.</p></blockquote>
<p>This is a definition of how <strong>polymorphism</strong> through inheritance is meant to work: it must always be possible to use an instance of a child class <em>in lieu</em> of a parent class without the client knowing about it.</p>
<p>Let’s make a simple example. Suppose we define a service to reverse the content of a string. We can have a simple implementation of that class in the following terms:</p>
<pre class="brush:csharp">
public class StringReverser
{
  public virtual string Reverse(string inputString)
  {
     // a simple algorithm optimized for
     // low memory consumption
  }
}
</pre>
<p>Notice how the <code>Reverse</code> method has been defined as virtual. This makes it possible to subclass and replace the implementation of the method with an algorithm that is faster (possibly trading off some memory; we are not concerned here with the nitty-gritty details of the actual implementation).</p>
<pre class="brush:csharp">
public class FastStringReverser : StringReverser
{
  public override string Reverse(string inputString)
  {
     // a fast algorithm implementation
     // using a bit more memory
  }
}
</pre>
<p>We introduce a factory whose responsibility is creating an object that knows how to reverse a string:</p>
<pre class="brush:csharp">
public class ReverserFactory
{
  public static StringReverser GetReverser()
  {
    // here we have the logic to decide which kind of Reverser to create
    return new StringReverser();
  }
}
</pre>
<p>Finally, we have client class that, for whatever reason, needs to reverse a string.</p>
<pre class="brush:csharp">
public class Client
{
  public void SomeMethod()
  {
    StringReverser reverser = ReverseFactory.GetReverser();
    string reversed = reverser.reverse(&quot;Contracts are fun&quot;);
    // do something with the reversed string
  }
}
</pre>
<p>In this case the <code>Client</code> class uses (<em>unknowingly</em>) an instance of a <code>StringReverser</code> class (which is the base class listed above). Since <code>FastStringReverser</code> is a subclass of <code>StringReverser</code>, if we rewrite the factory to return an instance of <code>FastStringReverser</code>, Client will continue to work:</p>
<pre class="brush:csharp">
public class ReverserFactory
{
  public static StringReverser GetReverser()
  {
    // now we return the fast implementation.
    // In a real world example, there will be some logic to decide
    // which class to instantiate according to the context,
    // configuration files, input parameters, etc...
    return new FastStringReverser();
  }
}
</pre>
<p>So here we see the LSP in action. Referring to the definition at the top of this post, we have the following correspondences:</p>
<ul>
<li><code>StringReverser</code> represents type T (the base type)</li>
<li><code>FastStringReverser</code> represents type S (the sub type)</li>
<li><code>Client</code> represents P (the code using T or a subtype of T)</li>
</ul>
<p>Note: here I have presented the example subclassing from a base class with a virtual method to match more closely the standard definition of the LSB. Even more common, though, is that T represents an <em>interface</em> and that two or more concrete classes implement that interface. The client will have a handle to such an interface and the actual implementation will be provided either by a factory method, service locator or through dependency injection.</p>
<p>The LSP is violated, for example, whenever a client class has some logic dealing with the particular type of the implementation (such as <a href="http://en.wikipedia.org/wiki/Run-time_type_information">Run Time Type Identification</a>: if the actual type is this, then do that, otherwise do that other thing &#8211; or something along this line).</p>
<h3>LSP and Contracts</h3>
<p>Unfortunately, there are much more subtle ways in which the LSP can be violated, even if the client code is &#8220;well behaving&#8221; as in the example above. The classical example goes under the name &#8220;A Square is Not A Rectangle&#8221;. <a href="http://www.mathsisfun.com/definitions/rectangle.html">According to geometry</a>, a square <i>is</i> a rectangle, but when it comes to software design&#8230; it is not!</p>
<p>The basic problem is that a square has an additional <em>invariant</em> with respect to the rectangle, which is that all the sides are equal and because of that you cannot independently change the height and the width like you would do with a rectangle; so if you have a <code>SetHeight</code> and <code>SetWidth</code> methods in the Rectangle, the Square should override those so that the invariant is always maintained: when the height is set by a client, internally the width is also set and vice versa. But the client might not expect this to happen! The client might make assumptions like the following:</p>
<pre class="brush:csharp">

// use a factory to create a rectangle passing width and height
Rectangle r = RectangleFactory.GetRectangle(4,5);

// change the dimensions
r.Width = 10;
// verify new dimensions
Assert.AreEqual(r.Width, 10);
Assert.AreEqual(r.Height, 5);

r.Height = 12;
// verify new dimensions
Assert.AreEqual(r.Width, 10);
Assert.AreEqual(r.Height, 12);
</pre>
<p>It&#8217;s easy to see that if the factory returns a Square, which internally always adjust one side to be equal to the other one, some of the assertions would fail. This means that the expectations of the client of dealing with a Rectangle square are no longer met, and the LSP is thus violated.<br />
A way to make it clear what really &#8220;being a rectangle&#8221; is meant to be is to introduce some contracts on the base class:</p>
<pre class="brush:csharp">
public class Rectangle
{
  private double width;
  private double height;

  public Rectangle(double w, double h) { width = w; height = h; }

  public virtual double Width
  {
    get { return width; }
    set
    {
      double oldHeight = height;
      width = value;
      // ensure that height has not changed
      Contract.Ensures(oldHeight = height);
    }
  }

  public virtual double Height
  {
    get { return height; }
    set
    {
      double oldWidth = width;
      height = value;
      // ensure that width has not changed
      Contract.Ensures(oldWidth = width);
    }
  }
}
</pre>
<p>Now, when it comes to inheriting from a class which specify some contracts, Design By Contract specifies the following <em>behavioral subtyping</em>:</p>
<ul>
<li> If a subclass overrides the behavior of a method of a base class (or implements and interface), the <em>preconditions</em> it specifies can only be equivalent to or <em>weaker</em> than the base class</li>
<li> If a subclass overrides the behavior of a method of a base class (or implements and interface), the <em>postconditions</em> it specifies can only be equivalent to or <em>stronger</em> than the base class.</li>
</ul>
<p>This mean that any potential subclass of <code>Rectangle</code> needs to satisfy the postconditions in each of his methods (and possibly add more). This explicitly rules out <code>Square</code> from being a candidate subclass (since a square cannot guarantee that changing one side does not affect the other).</p>
<p>It&#8217;s interesting to note that, quite symmetrically, the preconditions of a base class can only be weaker; this makes sense especially from the client perspective: if subclasses were allowed to require more stringent preconditions, a client might fail to meet some precondition and thus stop working when a service implementation is substituted with another, which is a clear violation of the LSP, which is all about <em>transparency</em>.</p>
<h3>Specifying Contracts for Interfaces and Abstract Classes</h3>
<p>In the example above, <code>Rectangle</code> was a concrete class with some virtual method. But how do you specify contracts with Microsoft Code Contracts for interfaces or abstract methods which do not have a concrete implementation?</p>
<p>For interfaces, you need to create a dummy class implementing the interface and link them through Attributes, like the following:</p>
<pre class="brush:csharp">
[ContractClass(typeof(IStringReverser))]
interface IStringReverser
{
  string Reverse(string s);
}

[ContractClassFor(typeof(IStringReverser))]
sealed class StringReverserContract : IStringReverser
{
  string Reverse(string s)
  {
    Contract.Requires(s != null);
    return String.Empty; // dummy return value
  }
}
</pre>
<p>Note how you have to use explicit interface implementation and the use of a dummy return value.</p>
<p>For abstract methods it&#8217;s similar:</p>
<pre class="brush:csharp">
[ContractClass(typeof(StringReverser))]
abstract class StringReverser
{
  public abstract string Reverse(string s);
}

[ContractClassFor(typeof(StringReverser))]
abstract class StringReverserContract : StringReverser
{
  public override string Reverse(string s)
  {
    Contract.Requires(s != null);
    return String.Empty; // dummy return value
  }
}
</pre>
<p>I urge you to refer to <a href="http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf">Microsoft Code Contracts documentation</a> for more information on how to specify contracts for interfaces and abstract methods.</p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/07/17/code-contracts-and-inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Contracts: Invariants</title>
		<link>http://stefanoricciardi.com/2009/07/01/code-contracts-invariants/</link>
		<comments>http://stefanoricciardi.com/2009/07/01/code-contracts-invariants/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 21:17:19 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=188</guid>
		<description><![CDATA[In a previous post we introduced Microsoft Code Contracts, and got an idea of what Design by Contract (DBC) is all about. It&#8217;s now time to introduce another powerful concept that complements and completes preconditions and postconditions when you specify the behavior of your object: class invariants. Invariants define all those conditions (or predicates, if [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F07%2F01%2Fcode-contracts-invariants%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F07%2F01%2Fcode-contracts-invariants%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In a <a href="http://stefanoricciardi.com/2009/06/26/introduction-to-microsoft-code-contracts-with-visual-studio-2008/">previous post</a> we introduced Microsoft Code Contracts, and got an idea of what Design by Contract (DBC) is all about. It&#8217;s now time to introduce another  powerful concept that complements and completes <em>preconditions </em>and <em>postconditions </em>when you specify the behavior of your object: class <em>invariants</em>.</p>
<p><em>Invariants </em>define all those conditions (or <em>predicates</em>, if you will) that are guaranteed to be true for all objects of a particular class throughout its life-cycle: these invariants need first to be met during construction and continue to hold before and after methods invocations.</p>
<p>Let&#8217;s consider a very simple implementation of a class that represents a calendar date, specified by day, month and year:</p>
<pre class="brush:csharp">
public class Date
{
  public short Day { get; }
  public short Month { get; }
  public short Year { get; }

  public Date(short dd, short mm, short yy)
  {
    Day = dd;
    Month = mm;
    Year = yy;
  }

  public void Increment()
  {
    // some tricky code to increment the day,
    // month (if needed) and year (if needed)
  }
}
</pre>
<p>Oversimplifying, such an object has some obvious invariants, or conditions that must always be met:</p>
<ul>
<li><code>Day</code>, <code>Month</code>, and <code>Year</code> may not be negative</li>
<li><code>Day</code> must be a number between 1 and 31 (let&#8217;s simplify and assume all months have the same days)</li>
<li><code>Month</code> must be a number between 1 and 12</li>
</ul>
<p>These conditions must be true upon successful creation of a <code>Date</code> object <em>and</em> after each invocation of <code>Increment()</code>.</p>
<p>With Code Contracts, one expresses invariants using a special method tagged with a <code>[ContractInvariantMethod]</code> attribute; it is usually named <code>ObjectInvariant</code> although this is just a convention: you can name it anything you like.</p>
<pre class="brush:csharp">

public class Date
{
  // ...
  // rest of the class as listing above

  [ContractInvariantMethod]
  protected void ObjectInvariant()
  {
    Contract.Invariant(this.Day &gt;= 0);
    Contract.Invariant(this.Day &lt;= 31);
    Contract.Invariant(this.Month &gt;= 0);
    Contract.Invariant(this.Month &lt;= 12);
    Contract.Invariant(this.Year &gt;= 0);
  }
}
</pre>
<p>You are not allowed to put any other code but the invariants; the method must have a <code>void</code> return type and be protected (unless the class is sealed of course).</p>
<p>Invariants are checked at the end of every public method (including constructors and excluding finalizers and methods implementing <code>IDisposable.Dispose()</code>) &#8211; in our example, every time a client of this class invokes the <code>Increment()</code> method, the invariants will be checked.</p>
<p>Invariants, along with pre and postconditions, are inherited by subclasses. We&#8217;ll see how this fits in a sound object oriented design in the next post.</p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/07/01/code-contracts-invariants/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Microsoft Code Contracts with Visual Studio 2008</title>
		<link>http://stefanoricciardi.com/2009/06/26/introduction-to-microsoft-code-contracts-with-visual-studio-2008/</link>
		<comments>http://stefanoricciardi.com/2009/06/26/introduction-to-microsoft-code-contracts-with-visual-studio-2008/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 13:16:35 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=131</guid>
		<description><![CDATA[(zdwfg7nay2) Design by Contract was first introduced by Bertrand Meyer, creator of the Eiffel programming language,  in his seminal book Object-oriented Software Construction. In a nutshell, DBC is based on the following principles: preconditions: a method imposes on the client a set of conditions that must be met in order for the method to be [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F06%2F26%2Fintroduction-to-microsoft-code-contracts-with-visual-studio-2008%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F06%2F26%2Fintroduction-to-microsoft-code-contracts-with-visual-studio-2008%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>(zdwfg7nay2)</p>
<p>
Design by Contract was first introduced by<a href="http://en.wikipedia.org/wiki/Bertrand_Meyer" target="_blank"> Bertrand Meyer</a>, creator of the Eiffel programming language,  in his seminal book <a href="http://www.amazon.co.uk/Object-oriented-Software-Construction-Prentice-Hall-Resource/dp/0136291554/ref=sr_1_1?ie=UTF8&amp;qid=1246018059&amp;sr=8-1" target="_blank">Object-oriented Software Construction</a>. In a nutshell, DBC is based on the following principles:</p>
<ul>
<li> <em>preconditions</em>: a method imposes on the client a set of conditions that must be met in order for the method to be invoked successfully (think about parameters validation).</li>
<li> <em>postconditions</em>: a set of properties are guaranteed by the method immediately after the execution (think about a return value that can only be positive, for example).</li>
<li> <em>invariants</em>: a set of properties on the class are assumed to hold before the method starts and are guaranteed to hold after the method completes (think about a field of the class that may not be negative, for example).</li>
</ul>
<p>A contract formalizes these three things. How can contracts, and <em>defensive programming</em> in general, help us developing better software? Bertrand Meyer explains it in this <a href="http://www.artima.com/intv/contracts.html">interview</a> from 2003:</p>
<blockquote><p>The main purpose of contracts is to help us build better software by organizing the communication between software elements through specifying, as precisely as possible, the mutual obligations and benefits that are involved in those communications. [...] relying on these  notions—that is to say, making sure when you write software that don&#8217;t just write  the implementation, but also write the more abstract properties underlying the  implementation in the form of contracts—provides a greatly added software  development experience in several respects. It helps ensure correctness in the first place,  helps debugging, helps testing, helps ensure inheritance is properly handled, helps  managers, provides a quite effective form of documentation, and a few others.</p></blockquote>
<p>Up to now, only a few languages supported DBC natively, and C# was not one of those. With .NET 4.0 Microsoft fills this gap with <a href="http://research.microsoft.com/en-us/projects/contracts/">Code Contracts</a>. It&#8217;s possible to download Code Contracts for Visual Studio 2008 for the Standard Edition and the Team System edition.</p>
<h3>A Basic Example</h3>
<p>Let&#8217;s see a basic example of how one can use Contracts in a simple class. (to try this on your own you need to install Code Contracts from <a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx">msdn web site</a>). In this case I have a class with a static method that simply inverts the content of a string (the choice of the algorithm here is irrelevant).</p>
<p>[sourcecode language="csharp"]<br />
using System;<br />
using System.Diagnostics.Contracts;</p>
<p>namespace TestContracts<br />
{<br />
  public class StringInverter<br />
  {<br />
    public static string Invert(string s)<br />
    {<br />
      // preconditions:<br />
      Contract.Requires(s != null);</p>
<p>      // postconditions;<br />
      Contract.Ensures(Contract.Result&lt;string&gt;().Length == s.Length);</p>
<p>      char[] reverted = new char[s.Length];<br />
      int i = 0;<br />
      foreach (char c in s)<br />
      {<br />
        reverted[s.Length - 1 - i ] = c;<br />
        i++;<br />
      }</p>
<p>      return new string(reverted);<br />
    }<br />
  }<br />
}<br />
[/sourcecode]</p>
<p>The first thing to notice is that we have added a reference to the <tt>System.Diagnostics.Contracts</tt> namespace. This is where the new library is located. For this to work you have also to add a reference in your project to the Microsoft.Contracts assembly that has come with the Code Contracts installation.</p>
<p><img class="aligncenter size-full wp-image-137" title="Contracts_VSReferences" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2009/06/contracts_vsreferences.jpg" alt="Contracts_VSReferences" width="225" height="207" /></p>
<p>The first method that we invoke on Contracts is a <em>precondition</em> that specifies that this method cannot accept an input string which is null (it would accept an empty string though). The second method is a <em>postcondition</em> asserting that this method guarantees that the string returned by this method will have the same size as the input string.</p>
<p>Obviously you are free to add more preconditions and/or postconditions if your domain logic requires so. But what exactly happens at run-time if either a precontion or a postcondition is not met? The answer is: it depends. After installing Code Contracts, project properties displays a new tab at the bottom named &#8220;Code Contracts&#8221; where you can tweak the contracts behavior for each of the build configurations that you have defined (Debug, Release, etc&#8230;).</p>
<p><a href="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2009/06/contracts_projectsproperties_1.jpg"><img class="aligncenter size-medium wp-image-147" title="Contracts Project Properties" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2009/06/contracts_projectsproperties_1.jpg?w=300" alt="Contracts Project Properties" width="300" height="225" /></a></p>
<p>Let&#8217;s concentrate on Runtime Checking for now: after you have checked it, you can decide which kind of contracts to enable; you should refer to official documentation for a complete explanation of all the options. For now, let&#8217;s just pick &#8220;Full&#8221; and check &#8220;Assert on contract failures&#8221;. With this choice, pre and postconditions will be tested at runtime and if any of them is not met a dialog will be shown detailing the failing condition.</p>
<p><img class="aligncenter size-full wp-image-152" title="Contracts_ProjectsProperties_2" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2009/06/contracts_projectsproperties_2.jpg" alt="Contracts_ProjectsProperties_2" width="497" height="96" /></p>
<p>So, let&#8217;s try calling the <tt>Invert</tt> method with a null string and let&#8217;s see what happens. Add the following code to the class above, compile and run.</p>
<p>[sourcecode language="csharp"]<br />
public static void Main()<br />
{<br />
  Console.WriteLine(Invert(null));<br />
}<br />
[/sourcecode]</p>
<p>This is what you should see:<br />
<img class="aligncenter size-full wp-image-155" title="ContractsAssertFailedPrecondition" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2009/06/contractsassertfailedprecondition.jpg" alt="ContractsAssertFailedPrecondition" width="496" height="347" /></p>
<p>As you can see, this looks exactly like using <tt>Debug.Assert</tt> calls from <tt>System.Diagnostics</tt> (many of us, myself included, used debug asserts in place of preconditions). In reality, contracts are much more powerful since</p>
<ul>
<li>you can not just enforce preconditions but also guarantee postconditions and other class invariants</li>
<li>contracts knows about class hierarchies: you can define contracts on interfaces and base classes and they will be inherited from derived classes</li>
<li>it&#8217;s possible to analyse compliance to contracts in a static way, even without running the code!</li>
</ul>
<p>We&#8217;ll discuss about all this in the next post. Stay tuned!</p>
<p><i>Next post in the series: <a href="http://stefanoricciardi.com/2009/07/01/code-contracts-invariants/">Code Contracts: Invariants</a></i>.</p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/visual+Studio+2008">Visual Studio 2008</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a></div>
]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/06/26/introduction-to-microsoft-code-contracts-with-visual-studio-2008/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
