<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Reshef's tip of the day</title>
	
	<link>http://jajahdevblog.com/reshef</link>
	<description>.net development tips</description>
	<pubDate>Thu, 03 Jan 2008 12:43:02 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/jajahdevblog/jffn" type="application/rss+xml" /><item>
		<title>Implicit construction of objects</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/210483919/</link>
		<comments>http://jajahdevblog.com/reshef/2008/01/03/implicit-construction-of-objects/#comments</comments>
		<pubDate>Thu, 03 Jan 2008 12:43:02 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[c#]]></category>

		<category><![CDATA[operator overloading]]></category>

		<category><![CDATA[Implicit conversion]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/2008/01/03/implicit-construction-of-objects/</guid>
		<description><![CDATA[An hidden and not commonly used feature of C# is the implicit constructor. It is so uncommon to see it, that one time (in band camp), when I saw it being used, it took me a while to understand what is going on&#8230;
Actually, implicit construction is not a real feature by itself, but rather a [...]]]></description>
			<content:encoded><![CDATA[<p>An hidden and not commonly used feature of C# is the implicit constructor. It is so uncommon to see it, that one time (<font color="#808080" size="1"><em>in band camp</em></font>), when I saw it being used, it took me a while to understand what is going on&#8230;</p>
<p>Actually, implicit construction is not a real feature by itself, but rather a by-product of implicit conversion between datatypes. Look <a href="http://msdn2.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx" target="_blank">here</a> for more information about implicit conversions.</p>
<p>Anyway, what it means, is that the object is being constructed by an invisible factory method.</p>
<p>Take a look at this options to instantiate an object:</p>
<pre class="code"><span style="color: rgb(43,145,175)">Telephone</span> tel = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">Telephone</span>(<span style="color: rgb(163,21,21)">&quot;972542221234&quot;</span>); <span style="color: rgb(0,128,0)">// By Ctor</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><span style="color: rgb(43,145,175)">Telephone</span> tel = <span style="color: rgb(43,145,175)">Telephone</span>.New(<span style="color: rgb(163,21,21)">&quot;972542221234&quot;</span>); <span style="color: rgb(0,128,0)">// Factory method</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><span style="color: rgb(43,145,175)">Telephone</span> tel = <span style="color: rgb(163,21,21)">&quot;972542221234&quot;</span>; <span style="color: rgb(0,128,0)">// Implicit Ctor</span></pre>
<p>Here is the implementation of the telephone object I used for this example. The implicit constructor implementation is bolded:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">Telephone
</span>{
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">readonly</span> <span style="color: rgb(0,0,255)">int</span> countryCode;
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">readonly</span> <span style="color: rgb(0,0,255)">int</span> areaCode;
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">readonly</span> <span style="color: rgb(0,0,255)">long</span> phoneNumber;

    <span style="color: rgb(0,0,255)">public</span> Telephone(<span style="color: rgb(0,0,255)">string</span> phoneNumber)
    {
        <span style="color: rgb(0,128,0)">// Dummy logic just for this example
</span>        <span style="color: rgb(0,0,255)">this</span>.countryCode =
            <span style="color: rgb(43,145,175)">Convert</span>.ToInt32(phoneNumber.Substring(0, 3));

        <span style="color: rgb(0,0,255)">this</span>.areaCode =
            <span style="color: rgb(43,145,175)">Convert</span>.ToInt32(phoneNumber.Substring(3, 2));

        <span style="color: rgb(0,0,255)">this</span>.phoneNumber =
            <span style="color: rgb(43,145,175)">Convert</span>.ToInt64(phoneNumber.Substring(5));
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">int</span> CountryCode
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> countryCode; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">int</span> AreaCode
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> areaCode; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">long</span> PhoneNumber
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> phoneNumber; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(43,145,175)">Telephone</span> New(<span style="color: rgb(0,0,255)">string</span> phoneNumber)
    {
        <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">Telephone</span>(phoneNumber);
    }

    <strong><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">implicit</span> <span style="color: rgb(0,0,255)">operator</span> <span style="color: rgb(43,145,175)">Telephone</span>(<span style="color: rgb(0,0,255)">string</span> phoneNumber)
    {
        <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(43,145,175)">Telephone</span>.New(phoneNumber);
    }</strong>
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This kind of syntax can help having less verbose code, and in software, less is usually more.</p>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2008/01/03/implicit-construction-of-objects/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2008/01/03/implicit-construction-of-objects/</feedburner:origLink></item>
		<item>
		<title>Throw meaningful exceptions!</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/210462190/</link>
		<comments>http://jajahdevblog.com/reshef/2008/01/03/throw-meaningful-exceptions/#comments</comments>
		<pubDate>Thu, 03 Jan 2008 11:10:14 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[Best practices]]></category>

		<category><![CDATA[Exception handling]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/2008/01/03/throw-meaningful-exceptions/</guid>
		<description><![CDATA[When you check for erroneous usage in the code you write, and there is a pretty good chance that this error was caused by a certain action (or more possibly the lack of an action), don&#8217;t just throw a meaningless exception that will leave the user of your code glancing helpless at the screen; give [...]]]></description>
			<content:encoded><![CDATA[<p>When you check for erroneous usage in the code you write, and there is a pretty good chance that this error was caused by a certain action (or more possibly the lack of an action), don&#8217;t just throw a meaningless exception that will leave the user of your code glancing helpless at the screen; give a guiding message that will help understand what he didn&#8217;t do correctly. Take a look at <a href="http://feeds.feedburner.com/~r/AyendeRahien/~3/179755867/Castle-Style-Errors.aspx" target="_blank">this</a> great example. </p>
<p>More helpful advices about exception handling are <a href="http://feeds.feedburner.com/~r/AyendeRahien/~3/196008962/Exception-handling-best-practices.aspx" target="_blank">here</a>, and <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2007/11/30/exception-handling-anti-pattern.aspx" target="_blank">this</a> article is a <strong>MUST READ</strong> in my opinion.</p>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2008/01/03/throw-meaningful-exceptions/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2008/01/03/throw-meaningful-exceptions/</feedburner:origLink></item>
		<item>
		<title>DynamicMethod full example</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/202237627/</link>
		<comments>http://jajahdevblog.com/reshef/2007/12/18/dynamicmethod-full-example/#comments</comments>
		<pubDate>Tue, 18 Dec 2007 14:14:53 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[code generation]]></category>

		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/?p=28</guid>
		<description><![CDATA[My last post described how to generate a dynamic method for object instantiation that its type is not known at compilation time.
I felt that the code snippets in that post were too technical and it was hard to understand how and when to use it in the real world. Therefore I created a small sample [...]]]></description>
			<content:encoded><![CDATA[<p>My last <a href="http://jajahdevblog.com/reshef/?p=26" target="_blank">post</a> described how to generate a dynamic method for object instantiation that its type is not known at compilation time.</p>
<p>I felt that the code snippets in that post were too technical and it was hard to understand how and when to use it in the real world. Therefore I created a small sample application that shows how and when it can be used.</p>
<p>The application is a small rule engine that gets a rule definitions file about a user&#8217;s credit, parses the rules, generates C# code and compiles the code on runtime. The rule engine is then instantiated by using a dynamic method.</p>
<p>The file <strong>UserCreditRules.rules</strong> contains the definitions of the rules and the dynamic method is generated in the file <strong>RulesFactory.cs</strong> by the method <strong>GenerateFactoryMethod(&#8230;)</strong>.</p>
<div class="wlWriterSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:d284e628-0348-40ee-a181-bf1cb555831b" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p>The sample application is <a href="http://jajahdevblog.com/reshef/wp-content/uploads/2007/12/dynamicmethodexample.zip" target="_blank">here.</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2007/12/18/dynamicmethod-full-example/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2007/12/18/dynamicmethod-full-example/</feedburner:origLink></item>
		<item>
		<title>Reflection and performance: DynamicMethod</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/202237628/</link>
		<comments>http://jajahdevblog.com/reshef/2007/12/17/reflection-and-performance-dynamicmethod/#comments</comments>
		<pubDate>Mon, 17 Dec 2007 11:07:42 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[code generation]]></category>

		<category><![CDATA[performance]]></category>

		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/?p=26</guid>
		<description><![CDATA[Reflection has a performance price, however, there are times that it just can&#8217;t be avoided, like when creating a new instance of a type generated and compiled at runtime. Since the type does not exist when compiling the code, it can&#8217;t be referenced and therefore can&#8217;t be instantiated by:
BaseType instance = new GeneratedType();
where BaseType is [...]]]></description>
			<content:encoded><![CDATA[<p>Reflection has a performance price, however, there are times that it just can&#8217;t be avoided, like when creating a new instance of a type generated and compiled at runtime. Since the type does not exist when compiling the code, it can&#8217;t be referenced and therefore can&#8217;t be instantiated by:</p>
<pre class="code"><span style="color: rgb(43,145,175)">BaseType</span> instance = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">GeneratedType</span>();</pre>
<p><a href="http://11011.net/software/vspaste"></a>where BaseType is the a type that GeneratedType inherits from.</p>
<p>So how to instantiate? </p>
<p>After generating the assembly, we have a reference to that assembly. The most naive and simple way is to call:</p>
<pre class="code"><span style="color: rgb(43,145,175)">BaseType</span> instance = (<span style="color: rgb(43,145,175)">BaseType</span>)generatedAssembly.
    CreateInstance(<span style="color: rgb(163,21,21)">&quot;GeneratedType&quot;</span>);</pre>
<p>But unfortunately this is also the worst way performance-wise, since on runtime first it looks for the name of the generated type through all the types in the assembly, then it looks for the appropriate constructor and then it instantiates the object. It can be optimized by caching the <a href="http://msdn2.microsoft.com/en-us/library/system.reflection.constructorinfo.aspx" target="_blank">ConstructorInfo</a> of the&#160; type and then calling it, which highly optimizes the instantiation time. There are other ways to achieve this goal but I am not going to go into it. For a thorough article and analysis take a look <a href="http://blogs.msdn.com/haibo_luo/archive/2005/11/17/494009.aspx" target="_blank">here</a> (the source code is <a href="http://blogs.msdn.com/haibo_luo/articles/494008.aspx" target="_blank">here</a>).</p>
<p>In order to get the best performance, we can use the <a href="http://msdn2.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx" target="_blank">DynamicMethod</a> class which generates IL code at runtime and creates a method out of it. This is done like this:</p>
<pre class="code"><span style="color: rgb(43,145,175)">Type</span> generatedType = <span style="color: rgb(43,145,175)">CompilerSimulator</span>.Compile().
    GetType(<span style="color: rgb(163,21,21)">&quot;<em>generated type name</em>&quot;</span>);

<span style="color: rgb(43,145,175)">DynamicMethod</span> dm =
    <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">DynamicMethod</span>(<span style="color: rgb(163,21,21)">&quot;GeneratedCtor&quot;</span>, generatedType,
        <span style="color: rgb(43,145,175)">Type</span>.EmptyTypes, <span style="color: rgb(0,0,255)">typeof</span>(<span style="color: rgb(43,145,175)"><em>ContainingType</em></span>).Module, <span style="color: rgb(0,0,255)">true</span>);

<span style="color: rgb(43,145,175)">ILGenerator</span> ilgen = dm.GetILGenerator();
ilgen.Emit(<span style="color: rgb(43,145,175)">OpCodes</span>.Nop);
ilgen.Emit(<span style="color: rgb(43,145,175)">OpCodes</span>.Newobj,
    generatedType.GetConstructor(<span style="color: rgb(43,145,175)">Type</span>.EmptyTypes));
ilgen.Emit(<span style="color: rgb(43,145,175)">OpCodes</span>.Ret);

<strong><span style="color: rgb(43,145,175)">GeneratedTypeFactoryMethod</span> factoryMethod =
    (<span style="color: rgb(43,145,175)">GeneratedTypeFactoryMethod</span>)dm.CreateDelegate(
    <span style="color: rgb(0,0,255)">typeof</span>(<span style="color: rgb(43,145,175)">GeneratedTypeFactoryMethod</span>));</strong></pre>
<p>The <strong>GeneratedTypeFactoryMethod</strong> is a delegate:</p>
<pre class="code"><span style="color: rgb(0,0,255)">delegate</span> <span style="color: rgb(43,145,175)">BaseType</span> <span style="color: rgb(43,145,175)">GeneratedTypeFactoryMethod</span>();</pre>
<p>Now, our code can return the generated method as delegate that will be called to to create a new instance of the generated type. By tests that I did I got results similar to direct instantiation (after setting up the factory delegate - but this happens only once).</p>
<p>Since writing IL code is not much fun, you can use a project named <a href="http://www.codeproject.com/KB/dotnet/runsharp.aspx" target="_blank">RunSharp</a> that wraps IL emitting with a high-level interface.</p>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2007/12/17/reflection-and-performance-dynamicmethod/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2007/12/17/reflection-and-performance-dynamicmethod/</feedburner:origLink></item>
		<item>
		<title>Null object pattern</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/202237629/</link>
		<comments>http://jajahdevblog.com/reshef/2007/12/10/null-object-pattern/#comments</comments>
		<pubDate>Mon, 10 Dec 2007 13:17:43 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[patterns]]></category>

		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/?p=25</guid>
		<description><![CDATA[There is a lot written about the null object pattern in the web, but it took me quite some time to find an example that I could relate to for null object.
Take a scenario where we have a email application with a message class:
public class Message
{
    private string m_recipient;
    [...]]]></description>
			<content:encoded><![CDATA[<p>There is a lot written about the null object pattern in the web, but it took me quite some time to find an example that I could relate to for null object.</p>
<p>Take a scenario where we have a email application with a message class:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">Message
</span>{
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">string</span> m_recipient;
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(43,145,175)">MailAccount</span> m_account;

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> Recipient
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_recipient; }
        <span style="color: rgb(0,0,255)">set</span> { m_recipient = <span style="color: rgb(0,0,255)">value</span>; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(43,145,175)">MailAccount</span> Account
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_account; }
        <span style="color: rgb(0,0,255)">set</span> { m_account = <span style="color: rgb(0,0,255)">value</span>; }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Lets say that we would like to view the massage pane window (pretty common requirement for a mail client), we will have to test the the <strong>Recipient</strong> and <strong>Account</strong> member for null value before accessing them.</p>
<p>Side effects when testing for null values is that we add code to the presentation logic which can possibly look like that:</p>
<pre class="code"><span style="color: rgb(0,0,255)">void</span> ShowMessage(<span style="color: rgb(43,145,175)">Message</span> m)
{
    <span style="color: rgb(0,0,255)">string</span> recipientDisplay = m.Recipient ?? <span style="color: rgb(43,145,175)">String</span>.Empty;

    <span style="color: rgb(0,0,255)">string</span> accountDisplay = m.Account ?? <span style="color: rgb(163,21,21)">&quot;NotSet&quot;</span>;
    <span style="color: rgb(0,0,255)">if</span>(m.Account == <span style="color: rgb(0,0,255)">null</span>)
    {
        accountDisplay = <span style="color: rgb(163,21,21)">&quot;NotSet&quot;</span>;
    }
    <span style="color: rgb(0,0,255)">else
</span>    {
        accountDisplay = m.Account.Name;
    }
    txtRecipient = recipientDisplay;
    txtAccountName = accountDisplay;
}</pre>
<p>This is a lot of code just for displaying two fields. We should also remember that a developer can possibly forget to test for null values and therefore to get a null reference exception.</p>
<p>The <strong>null object</strong> attempts to help here. One possible implementation is by implementing the Message class like this:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">Message
</span>{
    <span style="color: rgb(0,128,0)">// String.Empty is the null object for recipient
</span><strong>    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">string</span> m_recipient = <span style="color: rgb(43,145,175)">String</span>.Empty;
</strong>
    <span style="color: rgb(0,128,0)">// Set the &quot;NotSet&quot; account as the default value
</span>    <strong><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(43,145,175)">MailAccount</span> m_account = <span style="color: rgb(43,145,175)">MailAccount</span>.NotSet;
</strong>
    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> Recipient
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_recipient; }
        <span style="color: rgb(0,0,255)">set</span> { m_recipient = <span style="color: rgb(0,0,255)">value</span>; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(43,145,175)">MailAccount</span> Account
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_account; }
        <span style="color: rgb(0,0,255)">set</span> { m_account = <span style="color: rgb(0,0,255)">value</span>; }
    }
}</pre>
<p>Where the MailAccount class is implemented like that:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">MailAccount
</span>{
    <strong><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">readonly</span> <span style="color: rgb(43,145,175)">MailAccount</span> NotSet =
        <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">MailAccount</span>(<span style="color: rgb(163,21,21)">&quot;Not set&quot;</span>, <span style="color: rgb(163,21,21)">&quot;0.0.0.0&quot;</span>, <span style="color: rgb(0,0,255)">false</span>);</strong>

    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">string</span> m_name;
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">string</span> m_serverAddress;
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">bool</span> m_isSsl;

    <span style="color: rgb(0,0,255)">public</span> MailAccount(
        <span style="color: rgb(0,0,255)">string</span> name, <span style="color: rgb(0,0,255)">string</span> serverAddress, <span style="color: rgb(0,0,255)">bool</span> isSsl)
    {
        <span style="color: rgb(0,128,0)">//parameter validation&#8230;
</span>        m_name = name;
        m_serverAddress = serverAddress;
        m_isSsl = isSsl;
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> Name
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_name; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> ServerAddress
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_serverAddress; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">bool</span> IsSsl
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_isSsl; }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Here you can see that there is a static property called <strong>NotSet</strong> which is the null object. The field <strong>m_account</strong> is set by default to the <strong>NotSet</strong> account. The field<strong> m_recipient</strong> is set to <strong>String.Empty</strong> which also serves as a null object.</p>
<pre class="code"><span style="color: rgb(0,0,255)">void</span> ShowMessage(<span style="color: rgb(43,145,175)">Message</span> m)
{
    txtRecipient = m.Recipient;
    txtAccountName = m.Account.Name;
}</pre>
<p>Because we know that both Recipient and Account are <strong>not</strong> initialized to null, we can skip the null checking and thus we get much simpler and more readable code. </p>
<p>One thing that I like, is that now when the account is a null object (account not set), the default values will be displayed (&quot;Not set&quot; and address &quot;0.0.0.0&quot;). </p>
<p>A small problem with this kind of implementation is that the properties of the <strong>NotSet</strong> instance can be changed by reflection but the next part can solve that.</p>
<p>Another way to implement a null object is by subclassing or implementing an base interface. Based on the previous example, lets add an interface that represents an account:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">interface</span> <span style="color: rgb(43,145,175)">IMailAccount
</span>{
    <span style="color: rgb(0,0,255)">bool</span> IsSsl { <span style="color: rgb(0,0,255)">get</span>; }
    <span style="color: rgb(0,0,255)">string</span> Name { <span style="color: rgb(0,0,255)">get</span>; }
    <span style="color: rgb(0,0,255)">string</span> ServerAddress { <span style="color: rgb(0,0,255)">get</span>; }
}</pre>
<p>The MailAccount class will now look like that:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">MailAccount</span> : <span style="color: rgb(43,145,175)"><strong>IMailAccount</strong>
</span>{
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">string</span> m_name;
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">string</span> m_serverAddress;
    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">bool</span> m_isSsl;

    <span style="color: rgb(0,0,255)">public</span> MailAccount
        (<span style="color: rgb(0,0,255)">string</span> name, <span style="color: rgb(0,0,255)">string</span> serverAddress, <span style="color: rgb(0,0,255)">bool</span> isSsl)
    {
        <span style="color: rgb(0,128,0)">//parameter validation&#8230;
</span>        m_name = name;
        m_serverAddress = serverAddress;
        m_isSsl = isSsl;
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> Name
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_name; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> ServerAddress
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_serverAddress; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">bool</span> IsSsl
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> m_isSsl; }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Pay attention that the class now implements the <strong>IMailAccount</strong> interface and it does not contain the null object static field. The null object is implemented like this:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">NullMailAccount</span> : <span style="color: rgb(43,145,175)">IMailAccount
</span>{
    <span style="color: rgb(0,0,255)">public </span>NullMailAccount() {}

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">bool</span> IsSsl
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(0,0,255)">false</span>; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> Name
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(163,21,21)">&quot;NotSet&quot;</span>; }
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> ServerAddress
    {
        <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(163,21,21)">&quot;0.0.0.0&quot;</span>; }
    }
}</pre>
<p>and then the Message class will look like like this:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">Message
</span>{
    <strong><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">readonly</span> <span style="color: rgb(43,145,175)">IMailAccount</span>
        MailAccountNullObject = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">NullMailAccount</span>();</strong>

    <span style="color: rgb(0,128,0)">// String.Empty is the null object for recipient
</span>    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">string</span> m_recipient = <span style="color: rgb(43,145,175)">String</span>.Empty;

    <span style="color: rgb(0,128,0)">// Set the mail account null object
</span>    <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(43,145,175)">IMailAccount</span> m_account = <strong>MailAccountNullObject</strong>;
    &#8230;</pre>
<p>The usage of the Message class remains the same.</p>
<p>This implementation is also safe for reflection since the <strong>NullMailAccount</strong> class has no fields to change and in the class message, the field <strong>MailAccountNullObject</strong> is a readonly field which can&#8217;t be set by reflection.</p>
<p>So to conclude, the points that I liked the most about the null object pattern are:</p>
<p>1) Reduces significantly the chances of getting a null reference exception.</p>
<p>2) Defines a common behavior for fields that were not set yet such as the case of a common value to display.</p>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2007/12/10/null-object-pattern/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2007/12/10/null-object-pattern/</feedburner:origLink></item>
		<item>
		<title>Design by contract</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/202237630/</link>
		<comments>http://jajahdevblog.com/reshef/2007/12/06/design-by-contract/#comments</comments>
		<pubDate>Thu, 06 Dec 2007 10:36:31 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/?p=24</guid>
		<description><![CDATA[Well, just wanted to point out the existence of it but there is no need rewrite a perfectly written post&#160;so read it, NOW!
]]></description>
			<content:encoded><![CDATA[<p>Well, just wanted to point out the existence of it but there is no need rewrite a perfectly written <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2006/09/22/Design_2D00_by_2D00_Contract_3A00_-A-Practical-Introduction.aspx" target="_blank"><strong>post</strong></a><strong>&#160;</strong>so read it, NOW!</p>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2007/12/06/design-by-contract/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2007/12/06/design-by-contract/</feedburner:origLink></item>
		<item>
		<title>The Specification Pattern</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/202237631/</link>
		<comments>http://jajahdevblog.com/reshef/2007/12/05/the-specification-pattern/#comments</comments>
		<pubDate>Wed, 05 Dec 2007 08:38:04 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[c#]]></category>

		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/?p=20</guid>
		<description><![CDATA[This post is based on this post, which is a great post in my opinion and since it already exists I didn&#8217;t see the need to rewrite the post so I suggest you go read it first.
The stuff that I am going to add are few observations I have and small implementation enhancement that I [...]]]></description>
			<content:encoded><![CDATA[<p>This post is based on <a href="http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx" target="_blank">this</a> post, which is a great post in my opinion and since it already exists I didn&#8217;t see the need to rewrite the post so I suggest you go read it first.</p>
<p>The stuff that I am going to add are few observations I have and small implementation enhancement that I think helps the implementation to be even more intuitive. </p>
<p>First, a small overview.</p>
<p>Say you have a class <strong>User</strong> who has a name, country of residence and a birth date.</p>
<p>It makes sense that you have something like:</p>
<pre class="code"><span style="color: rgb(0,0,255)">if</span> (user.CountryOfResidence == <span style="color: rgb(43,145,175)">Country</span>.Chad ||
    user.CountryOfResidence == <span style="color: rgb(43,145,175)">Country</span>.Sudan)
{
    <span style="color: rgb(0,128,0)">// Do something&#8230;
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This code performs some special logic for a user that is coming from Africa and from a country that exists in our system. There is a good chance that code such as this condition is duplicated in a UI page and in a business logic service and maybe in some more places throughout the application. The problems with this are:</p>
<p>Unless the developer who wrote the code added documentation that states it checks that a user came from Africa, we can only guess what it means. It might just be a list of countries for all we know&#8230; You might say that it can be placed in a local private method like</p>
<pre class="code"><span style="color: rgb(0,0,255)">if</span> (IsUserFromAfrica(user))
{
    <span style="color: rgb(0,128,0)">// Do something
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>so now it describes what it means but this still doesn&#8217;t solve the code duplication problem. What if now Angola is supported as an African country as well? You will still have to go and change all the occurrences of the condition whether it is inline or wrapped in a method.</p>
<p>By using the Specification Pattern the code will be transformed to this:</p>
<pre class="code"><span style="color: rgb(0,0,255)">if</span> (<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">UserFromAfricaSpecification</span>().IsSatisfiedBy(user))
{
    <span style="color: rgb(0,128,0)">// Do something&#8230;
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Where <strong>UserFromAfricaSpecification</strong> is implemented like this:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">UserFromAfricaSpecification</span> :
    <span style="color: rgb(43,145,175)">Specification</span>&lt;<span style="color: rgb(43,145,175)">User</span>&gt;
{
    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">override</span> <span style="color: rgb(0,0,255)">bool</span> IsSatisfiedBy(<span style="color: rgb(43,145,175)">User</span> obj)
    {
        <span style="color: rgb(0,0,255)">return</span> obj.CountryOfResidence == <span style="color: rgb(43,145,175)">Country</span>.Chad ||
            obj.CountryOfResidence == <span style="color: rgb(43,145,175)">Country</span>.Sudan;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The base class <strong>Specification&lt;T&gt;</strong> can be found in the attached code.</p>
<p>By working with specifications like that, we get documented, reusable&#160; and independently testable &quot;libraries&quot; of specifications.</p>
<p>Since conditions usually are <strong>business rules</strong>, which are always difficult to maintain and manage, the specification pattern comes very handy and this is the one thing I like the most about it.</p>
<p>As I wrote before, <a href="http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx" target="_blank">this post</a> shows how the code is built. The code sample attached to my post is almost identical to the code there. The difference is mostly in one detail - specification composition can be performed using the &amp; and | operators, and the ! operator is also available. This means that you can write a specification like this:</p>
<pre class="code"><span style="color: rgb(0,0,255)">if</span> ((<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">UserOlderThanSpecification</span>(18) <strong>&amp;</strong>
    (!<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">UserFromAfricaSpecification</span>())).IsSatisfiedBy(user))
{
    <span style="color: rgb(0,128,0)">// Do something&#8230;
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Another use of the specification pattern is to define what we are looking for. The signature of the <strong>IsSatisfiedBy</strong> method matches the <strong>Predicate</strong> delegate signature and therefore can be used by the <strong>ForEach </strong>method of <strong>Array</strong> or <strong>List&lt;&gt;</strong> when looking for, say, a user who satisfies a certain condition:</p>
<pre class="code"><span style="color: rgb(43,145,175)">List</span>&lt;<span style="color: rgb(43,145,175)">User</span>&gt; africanUsers = allUsers.FindAll(
    <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">UserFromAfricaSpecification</span>().IsSatisfiedBy);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>where <strong>allUsers</strong> is of type <strong>List&lt;User&gt;</strong>.</p>
<p>What I still don&#8217;t like about the current implementation is the fact the the <strong>new</strong> keyword is used to instantiate a specification instance. I have few ideas about that so expect a follow-up.</p>
<div class="wlWriterSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:a3203180-cf1a-4103-a1d7-b3ae99b200e6" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p>The example code for this post is <a href="http://jajahdevblog.com/reshef/wp-content/uploads/2007/12/specificationpattern3.zip" target="_blank">here.</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2007/12/05/the-specification-pattern/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2007/12/05/the-specification-pattern/</feedburner:origLink></item>
		<item>
		<title>Creative operator overloading</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/202237632/</link>
		<comments>http://jajahdevblog.com/reshef/2007/12/03/creative-operator-overloading/#comments</comments>
		<pubDate>Mon, 03 Dec 2007 20:27:24 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[c#]]></category>

		<category><![CDATA[operator overloading]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/?p=17</guid>
		<description><![CDATA[This post is based on two facts about C#:
1) An operator is a method. It is a static method that receives 1 or 2 parameters, depends on the operator and returns a value.
2) The return value can be anything you want it to be. Usually the operator == returns a boolean, but it can return [...]]]></description>
			<content:encoded><![CDATA[<p>This post is based on two facts about C#:</p>
<p>1) An operator is a method. It is a static method that receives 1 or 2 parameters, depends on the operator and returns a value.</p>
<p>2) The return value can be anything you want it to be. Usually the operator == returns a boolean, but it can return any other data type.</p>
<p>The example I will show is about searching for a value in a generic list.</p>
<p>The .net generic list has a method called FindIndex with the following signature:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">int</span> FindIndex(<span style="color: rgb(43,145,175)">Predicate</span>&lt;T&gt; match);</pre>
<p><font face="Courier New">Predicate&lt;T&gt;</font> is a delegate that receives a parameter of type T for evaluation and returns a boolean in case the that there is a match according to the logic defined by the predicate. This works like This:</p>
<pre class="code"><span style="color: rgb(0,0,255)">int</span> indexOfUserToLookFor = usersList.FindIndex(<span style="color: rgb(0,0,255)">delegate</span>(<span style="color: rgb(43,145,175)">User</span> u)
{
    <span style="color: rgb(0,0,255)">return</span> u.FirstName == userToLookFor.FirstName &amp;&amp;
        u.LastName == userToLookFor.LastName;
});</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>where <font face="Courier New">usersList</font> is defined as <font face="Courier New">List&lt;User&gt;</font> and <font face="Courier New">User</font> is a class. The code above is not so elegant or readable. Having something like:</p>
<pre class="code"><span style="color: rgb(0,0,255)">int</span> indexOfUserToLookFor =
    usersList.FindIndex(<span style="color: rgb(43,145,175)">Where</span>.User == userToLookFor);</pre>
<p>would be much nicer and certainly more readable.</p>
<p>In order to enable such syntax, the two fact about operator overloading mentioned above come to play. The code:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">UserQuery
</span>{
    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <strong><span style="color: rgb(43,145,175)">Predicate</span>&lt;<span style="color: rgb(43,145,175)">User</span>&gt; <span style="color: rgb(0,0,255)">operator</span></strong> ==
        (<span style="color: rgb(43,145,175)">UserQuery</span> ignored, <span style="color: rgb(43,145,175)">User</span> other)
    {
        <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">Predicate</span>&lt;<span style="color: rgb(43,145,175)">User</span>&gt;(<span style="color: rgb(0,0,255)">delegate</span>(<span style="color: rgb(43,145,175)">User</span> u)
        {
            <span style="color: rgb(0,0,255)">return</span> u.FirstName == other.FirstName &amp;&amp;
                u.LastName == other.LastName;
        });
    }
    &#8230;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>does the trick. What this code means, is that when the operator == is used for object of type <strong>UserQuery</strong> (left hand side) and <strong>User</strong> (right hand side), return a <strong>Predicate&lt;User&gt;</strong> that contains the logic to match a user. Pay attention that the UserQuery parameter is named ignored since it is indeed, ignored. The predicate that is returned is the same as the predicate in the first <strong>FindIndex</strong> snippet therefore the functionality is the same.</p>
<p>The Where in the phrase &#8216;<span style="color: rgb(43,145,175)">Where</span>.User == userToLookFor&#8217; is just for nicer syntax. It is implemented simply as:</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">Where
</span>{
    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(43,145,175)">UserQuery</span> User
    {
        <span style="color: rgb(0,0,255)">get
</span>        {
            <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">User</span>.<span style="color: rgb(43,145,175)">UserQuery</span>();
        }
    }
}</pre>
<p>This post was inspired by the code generated using the <a href="http://www.ayende.com/Blog/archive/7186.aspx" target="_blank">NHibernate Query Generator</a> which uses this technic extensively. For an example of code by the NQG look <a href="https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/SampleApplications/NHibernate.Experiments.Blog" target="_blank">here</a>.</p>
<div class="wlWriterSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:ff62a43a-b7a2-4fef-bd78-a3c94913b53f" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p>The complete code example for this post can be downloaded <a href="http://jajahdevblog.com/reshef/wp-content/uploads/2007/12/creativeoperatoroverloading.zip" target="_blank">here</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2007/12/03/creative-operator-overloading/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2007/12/03/creative-operator-overloading/</feedburner:origLink></item>
		<item>
		<title>Tip of the day: DictionaryAdapter</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/202237633/</link>
		<comments>http://jajahdevblog.com/reshef/2007/11/25/tip-of-the-day-dictionaryadapter/#comments</comments>
		<pubDate>Sun, 25 Nov 2007 17:05:34 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[code generation]]></category>

		<category><![CDATA[reflection]]></category>

		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/?p=12</guid>
		<description><![CDATA[The DictionaryAdapter is a part of the Castle project but can be used as a standalone assembly.
The dictionary adapter lets you wrap a dictionary with an interface definition and access that dictionary through the interface. This gives the advantage of typed data access on top of a dictionary and don&#8217;t forget the intellisense in the [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.castleproject.org/components/dictionaryadapter/basics.html" target="_blank">DictionaryAdapter</a> is a part of the <a href="http://www.castleproject.org" target="_blank">Castle project</a> but can be used as a standalone assembly.</p>
<p>The dictionary adapter lets you <strong>wrap a dictionary with an interface definition</strong> and access that dictionary through the interface. This gives the advantage of typed data access on top of a dictionary and don&#8217;t forget the intellisense in the IDE.</p>
<p>The example I will use shows the use of a dictionary adapter in order to enable access to configuration data.&#160; It contains a class:</p>
<pre class="code"><span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;summary&gt;
///</span><span style="color: rgb(0,128,0)"> This class uses configuration.
</span><span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> Instead of accessing the configuration directly,
</span><span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> it receives it in the constructor.
</span><span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;/summary&gt;
</span><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">DataBaseAccess
</span>{
    <span style="color: rgb(0,0,255)">private</span> IDataBaseAccessConfig m_config;

    <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;param name=&quot;config&quot;&gt;</span><span style="color: rgb(0,128,0)">The configuration that
</span>    <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> this class uses to access the database.
</span>    <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;/param&gt;
</span>    <span style="color: rgb(0,0,255)">public</span> DataBaseAccess(IDataBaseAccessConfig config)
    {
        m_config = config;
    }

    <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> ConnectToDataBase()
    {
        <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">&quot;Server Ip: {0}&quot;</span>, m_config.ServerIp);
        <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">&quot;DataBase: {0}&quot;</span>, m_config.DataBaseName);
        <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">&quot;User: {0}&quot;</span>, m_config.UserName);
        <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">&quot;Password: {0}&quot;</span>, m_config.Password);
        <span style="color: rgb(43,145,175)">Console</span>.ReadLine();
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>As you can see, this class expects a config object that implements the the IDataBaseAccessConfig interface. This interface is defined as:</p>
<pre class="code"><span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;summary&gt;
///</span><span style="color: rgb(0,128,0)"> Defines the data for data base access.
</span><span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;/summary&gt;
</span><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">interface</span> <span style="color: rgb(43,145,175)">IDataBaseAccessConfig
</span>{
    <span style="color: rgb(0,0,255)">string</span> ServerIp { <span style="color: rgb(0,0,255)">get</span>;}
    <span style="color: rgb(0,0,255)">string</span> DataBaseName { <span style="color: rgb(0,0,255)">get</span>;}
    <span style="color: rgb(0,0,255)">string</span> UserName { <span style="color: rgb(0,0,255)">get</span>;}
    <span style="color: rgb(0,0,255)">string</span> Password { <span style="color: rgb(0,0,255)">get</span>;}
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>In the example, the database access data is defined in the appSettings section of the application configuration file. In order to pass it to the DataBaseAccess class, it is being wrapped like this:</p>
<pre class="code"><span style="color: rgb(0,128,0)">// In real world example the factory should be cached.
// Create the adapter on top of the configuration dictionary.
</span>IDataBaseAccessConfig configAdapter =
    <span style="color: rgb(0,0,255)">new</span> DictionaryAdapterFactory().
        GetAdapter&lt;IDataBaseAccessConfig&gt;(configData);</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>where the configAdapter is passed.</p>
<p>Now what happened here? The DictionaryAdapterFactory emit code in runtime that implements a wrapper class that implemets the IDataBaseAccessConfig interface and this class, when a property is being read, gets the value for the dictionary that is wrapped, in this case, the configData dictionary.</p>
<p>What is it good for?<br />
  <br /><strong>1)</strong> In my opinion, it is nicer to access an interface rather than passing a configuration dictionary to the class which involves querying the data by using string literals. </p>
<p><strong>2) </strong>When passing the data through the constructor instead of accessing the ConfigurationManager directly in the code we make our code better by preventing access to singletons, therefore making the code <strong>testable</strong> and agnostic to the real implementation, may it be the application configuration file, configuration defined in the database or any other implementation. </p>
<p><strong>3)</strong> Intellisense&#8230;</p>
</p>
<div class="wlWriterSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:240fb812-4d25-42d2-991d-aac37b27b84a" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p>The example solution is <a href="http://jajahdevblog.com/reshef/wp-content/uploads/2007/11/dictionaryadapterexample2.zip" target="_blank">here</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2007/11/25/tip-of-the-day-dictionaryadapter/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2007/11/25/tip-of-the-day-dictionaryadapter/</feedburner:origLink></item>
		<item>
		<title>Tip of the day #2: Dynamic proxies</title>
		<link>http://feeds.feedburner.com/~r/jajahdevblog/jffn/~3/202237634/</link>
		<comments>http://jajahdevblog.com/reshef/2007/11/25/tip-of-the-day-2-dynamic-proxies/#comments</comments>
		<pubDate>Sun, 25 Nov 2007 15:47:02 +0000</pubDate>
		<dc:creator>reshef</dc:creator>
		
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://jajahdevblog.com/reshef/?p=10</guid>
		<description><![CDATA[A dynamic proxy is an approach that is not fully natively supported in .net but natively exists in java.
What a proxy means, is to wrap an object with with wrapper that intercepts call to that object and does something in addition.
What is it good for? A naive example is to add a proxy that log [...]]]></description>
			<content:encoded><![CDATA[<p>A dynamic proxy is an approach that is not fully natively supported in .net but natively exists in java.</p>
<p>What a proxy means, is to wrap an object with with wrapper that intercepts call to that object and does something in addition.</p>
<p>What is it good for? A naive example is to add a proxy that log calls to methods of an object.</p>
<p>A more real world example is to use proxy in an <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank">O/R mapper</a>. The mapper can create proxies on top of the domain object and intercept calls to properties in order to fetch data from the db and track changes to the data that will later be persisted (<a href="http://en.wikipedia.org/wiki/Nhibernate" target="_blank">NHibernate</a> works this way).</p>
<p>The idea of dynamic proxy is to provide an implementation of an interceptor and attach it to the proxy. From now on, all calls to methods will pay through the interceptor which, for the logging example, logs every call to the method. Concrete examples can be found in the link at the bottom of this post.</p>
<p>The .net native implementation for dynamic proxies is by using <a href="http://msdn2.microsoft.com/en-US/library/system.contextboundobject.aspx" target="_blank">ContextBoundObject</a> or <a href="http://msdn2.microsoft.com/en-US/library/system.marshalbyrefobject.aspx" target="_blank">MarsalByRefObject</a>. This approach is limited since you have to inherit from one of these classes which is not clean.</p>
<p>There are several implementations of dynamic proxies that do not interfere with inheritance hierarchy of your code.    <br />Here are some examples:</p>
<p>1) <a href="http://www.codeproject.com/csharp/hamiltondynamicproxy.asp" target="_blank">Castle DynamicProxy</a></p>
<p>2) <a href="http://www.codeproject.com/dotnet/dynamicproxy.asp" target="_blank">DynamicProxy.NET</a></p>
<p>3) <a href="http://www.codeproject.com/cs/library/LinFuPart1.asp" target="_blank">LinFu</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jajahdevblog.com/reshef/2007/11/25/tip-of-the-day-2-dynamic-proxies/feed/</wfw:commentRss>
		<feedburner:origLink>http://jajahdevblog.com/reshef/2007/11/25/tip-of-the-day-2-dynamic-proxies/</feedburner:origLink></item>
	</channel>
</rss>
