<?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>Elegant Code &#187; C#</title>
	<atom:link href="http://elegantcode.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Sun, 12 Feb 2012 04:40:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>SqlBulkCopy for Generic List&lt;T&gt; (useful for Entity Framework &amp; NHibernate)</title>
		<link>http://elegantcode.com/2012/01/26/sqlbulkcopy-for-generic-listt-useful-for-entity-framework-nhibernate/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sqlbulkcopy-for-generic-listt-useful-for-entity-framework-nhibernate</link>
		<comments>http://elegantcode.com/2012/01/26/sqlbulkcopy-for-generic-listt-useful-for-entity-framework-nhibernate/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 02:12:26 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://elegantcode.com/?p=4786</guid>
		<description><![CDATA[A common complaint of the Entity Framework is slow insert times for larger datasets. Last night I was trying to insert a catalog of 15k products and it was taking a very long time (I gave up after 5 minutes). I recalled this post a while back from Mikael Eliasson demonstrating SqlBulkCopy using .NET. I [...]]]></description>
			<content:encoded><![CDATA[<p>A common complaint of the Entity Framework is slow insert times for larger datasets. Last night I was trying to insert a catalog of 15k products and it was taking a very long time (I gave up after 5 minutes). I recalled this <a href="http://mikee.se/Archive.aspx/Details/using_the_sqlbulkcopy_to_batch_inserts_20111129">post</a> a while back from Mikael Eliasson demonstrating SqlBulkCopy using .NET. I had used BCP in SQL server, but not from .NET. I took Mikael’s example and roughed out a reusable generic version below, which produced 15k inserts in 2.4s or +- 6200 rows per second. I upped it to 4 catalogs, 224392 rows in 39s, for +- 5750 rps (changing between 4 files). These are pretty decent records too, 41 columns and a few of the fields have a meaty char count. Good enough I say.</p>
<p><code><div id="gist-1681480" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="n">BulkInsert</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="kt">string</span> <span class="n">connection</span><span class="p">,</span> <span class="kt">string</span> <span class="n">tableName</span><span class="p">,</span> <span class="n">IList</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">list</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">using</span> <span class="p">(</span><span class="n">var</span> <span class="n">bulkCopy</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SqlBulkCopy</span><span class="p">(</span><span class="n">connection</span><span class="p">))</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">bulkCopy</span><span class="p">.</span><span class="n">BatchSize</span> <span class="p">=</span> <span class="n">list</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">bulkCopy</span><span class="p">.</span><span class="n">DestinationTableName</span> <span class="p">=</span> <span class="n">tableName</span><span class="p">;</span></div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">table</span> <span class="p">=</span> <span class="k">new</span> <span class="n">DataTable</span><span class="p">();</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">props</span> <span class="p">=</span> <span class="n">TypeDescriptor</span><span class="p">.</span><span class="n">GetProperties</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">T</span><span class="p">))</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">//Dirty hack to make sure we only have system data types </span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">//i.e. filter out the relationships/collections</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">Cast</span><span class="p">&lt;</span><span class="n">PropertyDescriptor</span><span class="p">&gt;()</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">Where</span><span class="p">(</span><span class="n">propertyInfo</span> <span class="p">=&gt;</span> <span class="n">propertyInfo</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">.</span><span class="n">Namespace</span><span class="p">.</span><span class="n">Equals</span><span class="p">(</span><span class="s">&quot;System&quot;</span><span class="p">))</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">.</span><span class="n">ToArray</span><span class="p">();</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">foreach</span> <span class="p">(</span><span class="n">var</span> <span class="n">propertyInfo</span> <span class="k">in</span> <span class="n">props</span><span class="p">)</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span>             </div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">bulkCopy</span><span class="p">.</span><span class="n">ColumnMappings</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">propertyInfo</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span> <span class="n">propertyInfo</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">table</span><span class="p">.</span><span class="n">Columns</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">propertyInfo</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span> <span class="n">Nullable</span><span class="p">.</span><span class="n">GetUnderlyingType</span><span class="p">(</span><span class="n">propertyInfo</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">)</span> <span class="p">??</span> <span class="n">propertyInfo</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">);</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC21'><br/></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">var</span> <span class="n">values</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">object</span><span class="p">[</span><span class="n">props</span><span class="p">.</span><span class="n">Length</span><span class="p">];</span></div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">foreach</span> <span class="p">(</span><span class="n">var</span> <span class="n">item</span> <span class="k">in</span> <span class="n">list</span><span class="p">)</span></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">for</span> <span class="p">(</span><span class="n">var</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">values</span><span class="p">.</span><span class="n">Length</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="p">=</span> <span class="n">props</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">GetValue</span><span class="p">(</span><span class="n">item</span><span class="p">);</span></div><div class='line' id='LC28'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC29'><br/></div><div class='line' id='LC30'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">table</span><span class="p">.</span><span class="n">Rows</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">values</span><span class="p">);</span></div><div class='line' id='LC31'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC32'><br/></div><div class='line' id='LC33'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">bulkCopy</span><span class="p">.</span><span class="n">WriteToServer</span><span class="p">(</span><span class="n">table</span><span class="p">);</span></div><div class='line' id='LC34'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC35'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1681480/94ccdef46951b9bb1953e41417301668a57efe98/gistfile1.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1681480#file_gistfile1.cs" style="float:right;margin-right:10px;color:#666">gistfile1.cs</a>
            <a href="https://gist.github.com/1681480">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>
</code></p>
<p><code><span style="font-family: verdana">This works off just a basic list of items which property names match the table column names. Given that most POCO based ORM’s generally match the schema exactly, it works great with EF code first objects.</span></code></p>
<p><code><span style="font-family: verdana">To use I just build up a list of objects, pick the connection string off the DbContext and then call BulkInsert to save to the DB. Note that in this case I am just adding items to a List&lt;T&gt;, not the EF DbSet&lt;T&gt;.</span></code></p>
<p><code><div id="gist-1681888" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>var imports = new List&lt;Product&gt;();</div><div class='line' id='LC2'>//Load up the imports</div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>//Pass in cnx, tablename, and list of imports</div><div class='line' id='LC5'>BulkInsert(context.Database.Connection.ConnectionString, &quot;Products&quot;, imports);</div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1681888/17c7489579af2a32c957f72f88396ab23d7f3b48/gistfile1.txt" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1681888#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a>
            <a href="https://gist.github.com/1681888">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>
</code></p>
<p><code><span style="font-family: verdana"></span></code></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2012/01/26/sqlbulkcopy-for-generic-listt-useful-for-entity-framework-nhibernate/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Dynamic in C# is Broken</title>
		<link>http://elegantcode.com/2011/08/11/dynamic-in-c-is-broken/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dynamic-in-c-is-broken</link>
		<comments>http://elegantcode.com/2011/08/11/dynamic-in-c-is-broken/#comments</comments>
		<pubDate>Thu, 11 Aug 2011 10:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/08/11/dynamic-in-c-is-broken/</guid>
		<description><![CDATA[Earlier this week, I ran into an issue while using the dynamic keyword in C#. I learned from C# in Depth that there are a couple of restrictions with dynamic, most notably when using extension methods or converting lambda expressions. But apparently there are more restrictions than meets the eye, which came as an unpleasant [...]]]></description>
			<content:encoded><![CDATA[<p align="justify"><a name="_GoBack"></a>Earlier this week, I ran into an issue while using the dynamic keyword in C#. I learned from <a href="http://elegantcode.com/2011/03/22/book-review-c-in-depth2nd-edition/">C# in Depth</a> that there are a couple of restrictions with dynamic, most notably when using extension methods or converting lambda expressions. But apparently there are more restrictions than meets the eye, which came as an unpleasant surprise. Let’s look at some code.</p>
<pre style="width: 100%; height: 250px" class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IPresenter
{
    <span class="kwrd">void</span> Start(dynamic startupData);
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> ISpecificPresenter : IPresenter
{}

<span class="kwrd">public</span> <span class="kwrd">class</span> SpecificPresenter : ISpecificPresenter
{
    <span class="kwrd">public</span> <span class="kwrd">void</span> Start(dynamic startupData)
    {
        <span class="rem">// ...</span>
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p align="justify">Here we have an interface called <i>IPresenter</i> with a single method on it named <i>Start</i>. Notice that the <i>Start</i> method has a single parameter which is defined as dynamic. We also have another interface called <i>ISpecificPresenter</i> that inherits from <i>IPresenter</i>. Finally we have a concrete class that implements the <i>ISpecificPresenter</i> interface. So far, so good.</p>
<p>Next we have a class called <i>Activator</i> that we use to kick-off a particular presenter.</p>
<pre style="width: 100%; height: 156px" class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Activator
{
    <span class="kwrd">public</span> <span class="kwrd">void</span> Start&lt;TPresenter&gt;(dynamic startupData)
        <span class="kwrd">where</span> TPresenter : IPresenter
    {
        var presenter = ObjectFactory.GetInstance&lt;TPresenter&gt;();
        presenter.Start(startupData);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p align="justify">The <i>Activator</i> class has a generic <i>Start</i> method with a parameter named <i>startupData</i> that is also dynamic. Here we simply get an instance of a requested presenter from <a href="http://structuremap.net/structuremap/">StructureMap</a> and call its <i>Start</i> method. This is how to call the <i>Start</i> method of the <i>Activator</i> class :</p>
<pre style="width: 100%; height: 41px" class="csharpcode">var activator = <span class="kwrd">new</span> Activator();
activator.Start&lt;ISpecificPresenter&gt;(<span class="kwrd">new</span>{});</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>When we run this code, we get the following exception:</p>
<blockquote>
<p align="justify">Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: &#8216;ISpecificPresenter&#8217; does not contain a definition for &#8216;Start&#8217;.</p>
</blockquote>
<p>This had me stumped for a while until I added a cast from <i>ISpecificPresenter</i> to <i>IPresenter</i> in the Start method of the Activator class.</p>
<pre style="width: 100%; height: 153px" class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Activator
{
    <span class="kwrd">public</span> <span class="kwrd">void</span> Start&lt;TPresenter&gt;(dynamic startupData)
        <span class="kwrd">where</span> TPresenter : IPresenter
    {
        var presenter = (IPresenter)ObjectFactory.GetInstance&lt;TPresenter&gt;();
        presenter.Start(startupData);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p align="justify">Now everything works as expected. But I’m not entirely sure why this isn’t behaving as I expected. I guess it has something to do with the fact that the <i>Start</i> method is defined on the <i>IPresenter</i> interface and not on the <i>ISpecificPresenter</i> interface.</p>
<p align="justify"><a href="http://elegantcode.com/wp-content/uploads/2011/08/image1.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2011/08/image_thumb1.png" width="447" height="112" /></a></p>
<p align="justify">Although I very much like the flexibility that dynamic objects bring to the C# language, I’m also starting to think that it might not be such a good idea to bring dynamic concepts to a statically typed language. Running into these kind of issues and limitations reinforces this growing opinion. </p>
<p>I would much appreciate it if anyone could enlighten me with a good explanation.</p>
<p>Until next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/08/11/dynamic-in-c-is-broken/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Book Review: C# in Depth&#8211;2nd Edition</title>
		<link>http://elegantcode.com/2011/03/22/book-review-c-in-depth2nd-edition/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=book-review-c-in-depth2nd-edition</link>
		<comments>http://elegantcode.com/2011/03/22/book-review-c-in-depth2nd-edition/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2011/03/22/book-review-c-in-depth2nd-edition/</guid>
		<description><![CDATA[I really learned a lot from reading the first edition of C# in Depth, so I was very glad that I finally found some time to make my way through the second edition. The content on C# 2.0 and 3.0 was only slightly revised compared to the first edition. Never change a winning combination . [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin: 0px 5px 0px 0px; display: inline; float: left" align="left" src="http://www.manning.com/skeet2/skeet2_cover150.jpg" width="183" height="228" /></p>
<p align="justify">I really learned a lot from reading the <a href="http://elegantcode.com/2008/10/20/book-review-c-in-depth/" target="_blank">first edition of C# in Depth</a>, so I was very glad that I finally found some time to make my way through the <a href="http://www.amazon.com/exec/obidos/ASIN/1935182471/elegantcode-20" target="_blank">second edition</a>. The content on C# 2.0 and 3.0 was only slightly revised compared to the first edition. Never change a winning combination <img src='http://elegantcode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . </p>
<p align="justify">But the final part of the book was the one that most interested me. This part discusses the features provided by the C# 4.0 compiler like optional parameters, named parameters, covariance/contravariance and last but not least, the dynamic keyword that got it’s very own chapter. The last chapter for this final part of the book is completely devoted to <a href="http://msdn.microsoft.com/en-us/devlabs/dd491992" target="_blank">Code Contracts</a>, which is not a language feature. I personally don’t like the way that Code Contracts are currently implemented by the .NET framework. I do hope that these concepts are going to be part of the C# language one day, which will be a major improvement regarding enforcing such contracts. Until that day, I think I’m going to stick with my own implementation.&#160;&#160; </p>
<p align="justify">Anyway, I still think that the title of this book is spot on. If you want to bring your C# skills to the next level, then this book will be you guide. This book is filled with knowledge that only a true C# language expert can deliver. Definitely worth the time and effort.</p>
<p align="justify">Happy reading.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2011/03/22/book-review-c-in-depth2nd-edition/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Black Art of P/Invoke and Marshaling in .NET</title>
		<link>http://elegantcode.com/2010/11/17/the-black-art-of-pinvoke-and-marshaling-in-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-black-art-of-pinvoke-and-marshaling-in-net</link>
		<comments>http://elegantcode.com/2010/11/17/the-black-art-of-pinvoke-and-marshaling-in-net/#comments</comments>
		<pubDate>Wed, 17 Nov 2010 20:13:36 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/17/the-black-art-of-pinvoke-and-marshaling-in-net/</guid>
		<description><![CDATA[Last week I finally managed to hunt down and resolve a bug that I had been chasing for quite some time. A couple of years ago I built an ASP.NET web service that makes use of a native library to provide most of its functionality. This native DLL exposes a C API, much like the [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I finally managed to hunt down and resolve a bug that I had been chasing for quite some time. A couple of years ago I built an ASP.NET web service that makes use of a native library to provide most of its functionality. This native DLL exposes a C API, much like the Win32 API, that we’ve been using for integrating a highly-expensive product from a certain vendor into our system.</p>
<p>I didn’t notice any issues during the initial development of this web service, in fact, I was very pleased with how easy it was to use and integrate this API. Until this very day, I still consider this as one of the nicest and most stable C API’s I’ve ever come across. After I finished most of the features for the web service, I ran a couple of load tests in order to determine whether the respective product could withstand a fair amount of requests and also to detect any glitches that might come up in the interop layer. Nothing major turned up, so we decided to bring this service into production and go on with out merry lives. </p>
<p>Aft first we didn’t receive any complaints. Everything worked out as expected, until earlier this year, we noticed some failures of the application pool for our web service in IIS. The event log showed some random crashes of the CLR (= very bad) with some highly obscure error message. These issues occurred completely random. One day, there were about five to six application pool crashes after which it behaved very stable again, sometimes for months in a row. </p>
<p>After doing some investigation on my part, which also involved stretching my shallow knowledge of <a href="http://en.wikipedia.org/wiki/WinDbg" target="_blank">WinDbg</a>, I found out that .NET runtime was doing a complete shutdown after an <a href="http://msdn.microsoft.com/en-us/library/system.accessviolationexception.aspx" target="_blank">AccessViolationException</a> being thrown. This exception reported the following issue:</p>
<blockquote><p><em>Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</em></p>
</blockquote>
<p>The first thing I considered was a memory leak turning up somewhere. It’s unmanaged code after all, right? After reviewing the code that uses the imported native functions, I discovered two potential memory leaks that might come up during some edge case scenarios. So I fixed those, but unfortunately it didn’t resolve the problem.</p>
<p>I tried a couple of other things and also approached the issue from a couple of different angles. I’m not going to bore you with the details here, but it clearly didn’t solve anything. I started to become a bit frustrated with this problem. At some point, I was even convinced that this was all caused by the native library itself and not in our code, which is a classic mistake in most long debugging sessions. The good thing was that I was able to reproduce the problem on my machine, by running the load tests with a particular high load. I noticed that there was also a certain pattern in the number of requests between each crash of the application pool.</p>
<p>Vastly determined to fix this, I decided to read up on some information about P/Invoke and marshaling in .NET. I ended up reading <a href="http://dotnetdebug.net/2006/04/17/pinvoke-and-memory-related-issues/" target="_blank">this blog post on P/Invoke and memory related issues</a>. While it didn’t provide a clear solution, reading that blog post certainly guided me in the right direction. I started to turn off feature by feature until I was able to isolate the cause of the crash to a single function call. The native function in question has the following signature:</p>
<pre class="csharpcode"><span class="kwrd">char</span>* FunctionThatReturnsAString();</pre>
<p>As it turned out, I created the following P/Invoke prototype for this native function in C#:</p>
<pre class="csharpcode">[DllImport(<span class="str">&quot;SomeProduct.dll&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> String FunctionThatReturnsAString();</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>At first sight (and even after a number of subsequent reviews), there seems to be nothing wrong with the way the <em>char *</em> return value is marshaled to a <em>String</em>. I started reading the excellent documentation for this function again, and it explicitly mentioned that the caller should not cleanup the memory for the return value. The allocated memory for the return value is always cleaned up by the native function itself. </p>
<p>Doing some more research on marshaling strings, I found out that in case the native function does its own cleanup, an <em><a href="http://msdn.microsoft.com/en-us/library/system.intptr(VS.71).aspx" target="_blank">IntPtr</a></em> must be returned by the C# prototype declaration instead of a <em>String</em>. </p>
<p>Most c-style strings returned by native functions must be cleaned up by the calling code. For this common scenario, when the return value is marshaled to a <em>String</em>, the interop marshaler assumes that it has to free the unmanaged memory returned by the function. In our case, this actually means that the interop marshaler tried to cleanup memory that at some point was already freed up by the native function or vice versa.&#160;&#160; </p>
<p>So I changed the return value for the P/Invoke prototype declaration to an <em>IntPtr</em>. This way, the interop marshaler does not automatically free the memory that is referenced by the <em>IntPtr</em>.</p>
<pre class="csharpcode">[DllImport(<span class="str">&quot;SomeProduct.dll&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr FunctionThatReturnsAString();</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Marshaling the data referenced by the <em>IntPtr</em> to a string is quite easy. This can be done using the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.ptrtostringauto.aspx" target="_blank">Marshal.PtrToStringAuto</a> method. </p>
<p>The lesson I learned here is that we need to watch out for these kind of issues when using interop with unmanaged code. On the surface everything seems to work out just fine, but one can still run into some nasty issues afterwards. Carefully considering how to correctly marshal data from and to unmanaged code is an essential technique and sometimes feels like a black art that is not suited for the faint of heart, like myself <img src='http://elegantcode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/17/the-black-art-of-pinvoke-and-marshaling-in-net/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Parse That XML!</title>
		<link>http://elegantcode.com/2010/08/07/dont-parse-that-xml/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dont-parse-that-xml</link>
		<comments>http://elegantcode.com/2010/08/07/dont-parse-that-xml/#comments</comments>
		<pubDate>Sat, 07 Aug 2010 20:51:53 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/08/07/dont-parse-that-xml/</guid>
		<description><![CDATA[I’ve talked a few times about how the best code you can write is code you never write.&#160; One of the major places I end up seeing developer writing code that they don’t need to write is when parsing XML. A word of caution before I go into how to not have to parse XML! [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve talked a few times about how the <a href="http://elegantcode.com/2010/06/06/the-best-code-you-will-ever-write/">best code you can write</a> is code you never write.&#160; One of the major places I end up seeing developer writing code that they don’t need to write is when parsing XML.</p>
<p><strong><em>A word of caution before I go into how to not have to parse XML!</em></strong></p>
<p><em>What I am going to describe is not always going to be the best solution.&#160; It is an easy solution that will cover simple processing of XML files.&#160; For a large XML file, the solutions I am going to suggest might be memory intensive and take too long.</em></p>
<p><em></em></p>
<h2>Seems like everyone is doing it</h2>
<p>I’ve walked into so many software development shops and seen code to parse XML files.&#160; It seems to be one of those really common things that not enough developers realize can be completely automated.</p>
<p>I have started to wonder if it is self-propagating.&#160; If developers have a tendency to see it being manually parsed in one place, assume that there is not a better way, then propagate that manual parsing to the next place they go.</p>
<h2>Why is it so bad?</h2>
<p>First of all, it is not an easy task to parse XML.&#160; Even when using an XML parsing library there is a large amount of code that has to be written, especially for a complex XSD.</p>
<p>XML parsing code is also very fragile.&#160; If the structure of an XML file changes, the code will have to be modified, and the modification can have cascading effects.</p>
<p>Manually generated XML parsing code cannot be regenerated if the structure of the XML changes.</p>
<p>Most importantly, any code you have to write runs the risk of introducing bugs and complexity into the system.</p>
<h2>It’s so simple you wouldn’t believe it</h2>
<p>So, how simple is it to automatically parse XML into objects?</p>
<p>Very simple.&#160; First I am going to give you the basic pattern, then I am going to tell you how to do it in both C# and Java.</p>
<p><strong>Basic pattern:</strong></p>
<ol>
<li>Use a tool to generate an inferred XSD from your XML file.&#160; (You can skip this step if you already have an XSD file.) </li>
<li>Use a code generation tool to generate your classes automatically from the XSD file. </li>
<li>In your code, deserialize your XML file into an object tree using the framework you generated the classes from. </li>
</ol>
<p><strong>If you are doing something more complex than this, without a really good reason, you are doing it wrong!</strong></p>
<p>Learning how to do this in your language of choice is a very important tool to put into your tool bag.&#160; There are many times that I have run into the need to parse XML files, where I have saved many hours of development time, by knowing how to automatically deserialize my XML files into objects.</p>
<p>There are two main ways in which XML serialization frameworks work.</p>
<ol>
<li>Serializers that auto-generate the classes from the XSD files.</li>
<li>Serializers that use annotations or attributes on classes.</li>
</ol>
<p>Using a serializer that auto-generates the classes from an XSD is the easiest to use and can work in most cases.&#160; If you need more control over the generation of the XML, you might want to use an attribute or annotation based framework.</p>
<p>One of the biggest barriers in getting started with an XML framework is knowing what to use and how to use it.&#160; I am going to cover 3 options that will get you going for C#, Java SE, and Java Android development.</p>
<h2>C# (XSD.exe)</h2>
<p>XML serialization is so easy in C# because it is built right into the .NET framework.</p>
<p>The only real piece of magic you need to know is the <a href="http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.80).aspx">XSD.exe</a> tool which is installed with Visual Studio.&#160; This one tool can be run to infer an XSD from your XML file and then again to take that XSD and produce fully serializable / deserializable classes.</p>
<p>If you have an XML file named myFile.xml, you can simply go to the Visual Studio command prompt and type:</p>
<p><em>xsd myFile.xml</em></p>
<p>Which will produce a myFile.xsd.</p>
<p>Then type</p>
<p><em>xsd myFile.xsd /c</em></p>
<p>This will generate a set of classes that you can add to your project, and then you can deserialize an xml file with this simple code:</p>
<div id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> XmlSerializer serializer = </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> <span style="color: #0000ff">new</span> XmlSerializer(<span style="color: #0000ff">typeof</span>(MyFile));</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span> Stream reader = <span style="color: #0000ff">new</span> FileStream(<span style="color: #006080">&quot;myFile.xml&quot;</span>,FileMode.Open);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span> MyFile myFile = (MyFile) serializer.Deserialize(reader);</pre>
<p><!--CRLF--></div>
</div>
<div>&#160;</div>
<div>It really is that simple.&#160; <strong>There is no excuse for hand writing XML parsing code when you can literally take an XML file you have never seen before and turn it into an object in memory in 10 minutes.</strong></div>
<div><strong></strong></div>
<div>The serialization framework and XSD tool provide options for using attributes to control how the XML is generated also.</div>
<h2>Java (JAXB)</h2>
<p>The steps are slightly more complicated with <a href="http://www.oracle.com/technetwork/articles/javase/index-140168.html">JAXB</a>, but it is still fairly easy.</p>
<p>First we have to generate an XSD file from an XML file.&#160; JAXB doesn’t do this itself as far as I know, but there is another tool we can use called <a href="http://www.thaiopensource.com/relaxng/trang.html">Trang</a>.</p>
<p>First step, download Trang, then run it like so:</p>
<p><em>java –jar trang.jar –I xml –O xsd myFile.xml myFile.xsd</em></p>
<p>You can also use the XSD.exe tool from Visual Studio if you have it installed or download it.&#160; There are a few other tools out there as well.</p>
<p>Once you have the XSD file, or if you already had one you had written, you need to generate Java classes using JAXB’s tool like so:</p>
<p><em>xjc –p my.package.name myFile.xsd –d myDirectory</em></p>
<p>Running this command will produce Java files that represent the elements in your XML document.</p>
<p>Finally, to create your objects you can use the JAXB unmarshaller.</p>
<div id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> JAXBContext jc = JAXBContext.newInstance(<span style="color: #006080">&quot;my.package.name&quot;</span>);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> Unmarshaller unmarshaller = jc.createUnmarshaller();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span> MyFile myFile = (MyFile) unmarshaller.unmarshal(<span style="color: #0000ff">new</span> File( <span style="color: #006080">&quot;myFile.xml&quot;</span>));</pre>
<p><!--CRLF--></div>
</div>
<p>Not as simple as the C# example, but really quite simple.&#160; I’ve omitted the steps like downloading JAXB and adding it to your class path, but you can see that the process really is not very painful at all.</p>
<p>JAXB also provides some options for customizing the serialization and deserialization.</p>
<h2>Android (Simple XML)</h2>
<p>You can’t use JAXB with Android.&#160; It seems like because of the Dalvik VM, the reflection part of JAXB doesn’t work.</p>
<p>I found a pretty good and small XML framework that I am using in my Android app that seems to do the trick nicely.&#160; You have to annotate your classes and create them by hand, but it is very simple and straightforward to do so.</p>
<p>The tool is called “<a href="http://simple.sourceforge.net/">Simple XML</a>.”</p>
<p>You can find lots of examples on the “tutorial” tab on the web page.</p>
<p>Basically, you download Simple XML, add the jars to you class path, and create class files with some annotations to specify how to deserialize or serialize your XML.</p>
<p>Here is a small example of an annotated class, from the Simple XML website.</p>
<div id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> @Root</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Example {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>    @Element</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span>    <span style="color: #0000ff">private</span> String text;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span>    @Attribute</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum8">   8:</span>    <span style="color: #0000ff">private</span> <span style="color: #0000ff">int</span> index;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum9">   9:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum10">  10:</span>    <span style="color: #0000ff">public</span> Example() {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum11">  11:</span>       <span style="color: #0000ff">super</span>();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum12">  12:</span>    }  </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum13">  13:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum14">  14:</span>    <span style="color: #0000ff">public</span> Example(String text, <span style="color: #0000ff">int</span> index) {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum15">  15:</span>       <span style="color: #0000ff">this</span>.text = text;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum16">  16:</span>       <span style="color: #0000ff">this</span>.index = index;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum17">  17:</span>    }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum18">  18:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum19">  19:</span>    <span style="color: #0000ff">public</span> String getMessage() {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum20">  20:</span>       <span style="color: #0000ff">return</span> text;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum21">  21:</span>    }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum22">  22:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum23">  23:</span>    <span style="color: #0000ff">public</span> <span style="color: #0000ff">int</span> getId() {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum24">  24:</span>       <span style="color: #0000ff">return</span> index;</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum25">  25:</span>    }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum26">  26:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>&#160;</p>
<p>To deserialize this xml you just use the following code.</p>
<div id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> Serializer serializer = <span style="color: #0000ff">new</span> Persister();</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> File source = <span style="color: #0000ff">new</span> File(<span style="color: #006080">&quot;example.xml&quot;</span>);</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span> Example example = serializer.read(Example.<span style="color: #0000ff">class</span>, source)</pre>
<p><!--CRLF--></div>
</div>
<p>Very simple and straightforward.&#160; The only downside is generating the Java class files yourself, but that isn’t really very hard to do using the annotations.</p>
<h2>No excuses</h2>
<p>So there you have it, XML serialization frameworks abound to make your life easier when dealing with XML.&#160; For most simple cases you should never handwrite XML parsing code, even when using a library to help you do it.</p>
<p>Now that I’ve shown you how easy it is, there really are no excuses!</p>
<h6>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.&#160; Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.&#160; Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/08/07/dont-parse-that-xml/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>CreateDelegate&lt;T&gt; &#8211; An Exercise in Using Expressions</title>
		<link>http://elegantcode.com/2010/07/30/createdelegatet-an-exercise-in-using-expressions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=createdelegatet-an-exercise-in-using-expressions</link>
		<comments>http://elegantcode.com/2010/07/30/createdelegatet-an-exercise-in-using-expressions/#comments</comments>
		<pubDate>Fri, 30 Jul 2010 22:31:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/07/30/createdelegatet-an-exercise-in-using-expressions/</guid>
		<description><![CDATA[In a previous blog post I showed a basic example of how to use the Delegate.CreateDelegate() method as an alternative to the slow MethodInfo.Invoke() for dynamically invoking a method of a class at runtime. The only downside of using CreateDelegate is that its not strongly typed. This is usually not a problem when the signature [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://elegantcode.com/2010/01/28/calling-non-public-methods/">previous blog post</a> I showed a basic example of how to use the <a href="http://msdn.microsoft.com/en-us/library/system.delegate.createdelegate.aspx">Delegate.CreateDelegate()</a> method as an alternative to the slow <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx">MethodInfo.Invoke()</a> for dynamically invoking a method of a class at runtime. The only downside of using <em>CreateDelegate</em> is that its not strongly typed. This is usually not a problem when the signature of the method that must be invoked is known at compile as is the case in the example shown in the blog post mentioned earlier. </p>
<pre class="csharpcode">var subject = <span class="kwrd">new</span> Subject();
var doSomething = (Func&lt;String, String&gt;)
    Delegate.CreateDelegate(<span class="kwrd">typeof</span>(Func&lt;String, String&gt;), subject, <span class="str">&quot;DoSomething&quot;</span>);
Console.WriteLine(doSomething(<span class="str">&quot;Hello Freggles&quot;</span>));</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Here we’re simply able to cast the result to the requested delegate type. But what if a generic method must be invoked for which the type parameters can vary at runtime? You can still use the <em>CreateDelegate</em> method, but you can’t cast the result to a strongly typed delegate type. This means that in order to invoke the created delegate, the <a href="http://msdn.microsoft.com/en-us/library/system.delegate.dynamicinvoke.aspx">DynamicInvoke</a> method must be called on the returned <a href="http://msdn.microsoft.com/en-us/library/system.delegate.aspx">Delegate</a> object. This has the nasty side effect that when the original method being called throws an exception, the <em>DynamicInvoke</em> method wraps the original exception in a <a href="http://msdn.microsoft.com/en-us/library/system.reflection.targetinvocationexception.aspx">TargetInvocationException</a>.&#160;&#160; </p>
<p>So in order to find a better way and also exercise my <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx">Expressions-fu</a>, I tried to come up with a CreateDelegate&lt;T&gt; extension method that can be used to a create a strongly typed delegate for a <em>MethodInfo</em> object.</p>
<p>Suppose we have to dynamically invoke a method with the following signature:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> Map&lt;TDomainEvent, TEvent&gt;(TDomainEvent domainEvent, TEvent @<span class="kwrd">event</span>)
    <span class="kwrd">where</span> TDomainEvent : IDomainEvent
    <span class="kwrd">where</span> TEvent : IEvent
{
    ...
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Given an instance of <em>IDomainEvent</em> and <em>IEvent</em>, using the CreateDelegate&lt;T&gt; extension method that I’m about to show, we can dynamically invoke this method using the following code:</p>
<pre class="csharpcode">var action = GetType()
    .GetMethod(<span class="str">&quot;Map&quot;</span>, methodBindings)
    .MakeGenericMethod(domainEvent.GetType(), @<span class="kwrd">event</span>.GetType())
    .CreateDelegate&lt;Action&lt;IDomainEvent, IEvent&gt;&gt;(<span class="kwrd">this</span>);

action(domainEvent, @<span class="kwrd">event</span>);</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Here we determine a specific <em>MethodInfo</em> object for the <em>Map</em> method using the types of the event objects we have. Now here’s the code for the strongly typed <em>CreateDelegate</em> extension method.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> MethodInfoExtensions
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> TDelegate CreateDelegate&lt;TDelegate&gt;(<span class="kwrd">this</span> MethodInfo method,
                                                      Object instance)
        <span class="kwrd">where</span> TDelegate : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> CreateCachedDelegate&lt;TDelegate&gt;(method,
            (typeArguments, parameterExpressions) =&gt;
            {
                Expression&lt;Func&lt;Object&gt;&gt; instanceExpression = () =&gt; instance;
                <span class="kwrd">return</span> Expression.Call(Expression.Convert(instanceExpression.Body,
                                                          instance.GetType()),
                                       method.Name,
                                       typeArguments,
                                       ProvideStrongArgumentsFor(method,
                                                                 parameterExpressions));
            });
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> TDelegate CreateDelegate&lt;TDelegate&gt;(<span class="kwrd">this</span> MethodInfo method)
        <span class="kwrd">where</span> TDelegate : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> CreateCachedDelegate&lt;TDelegate&gt;(method,
            (typeArguments, parameterExpressions) =&gt;
                Expression.Call(method.DeclaringType, method.Name, typeArguments,
                                ProvideStrongArgumentsFor(method, parameterExpressions)));
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> TDelegate CreateCachedDelegate&lt;TDelegate&gt;(MethodBase method,
        Func&lt;Type[], ParameterExpression[], MethodCallExpression&gt; getCallExpression)
        <span class="kwrd">where</span> TDelegate : <span class="kwrd">class</span>
    {
        var @<span class="kwrd">delegate</span> = GetFromCache&lt;TDelegate&gt;();
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == @<span class="kwrd">delegate</span>)
        {
            @<span class="kwrd">delegate</span> = CreateDelegate&lt;TDelegate&gt;(method, getCallExpression);
            StoreInCache(@<span class="kwrd">delegate</span>);
        }

        <span class="kwrd">return</span> @<span class="kwrd">delegate</span>;
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> TDelegate GetFromCache&lt;TDelegate&gt;()
    {
        Object delegateObj;
        <span class="kwrd">if</span>(_delegateCache.TryGetValue(<span class="kwrd">typeof</span>(TDelegate), <span class="kwrd">out</span> delegateObj))
            <span class="kwrd">return</span> (TDelegate)delegateObj;

        <span class="kwrd">return</span> <span class="kwrd">default</span>(TDelegate);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> StoreInCache&lt;TDelegate&gt;(TDelegate @<span class="kwrd">delegate</span>)
    {
        _delegateCache.TryAdd(<span class="kwrd">typeof</span>(TDelegate), @<span class="kwrd">delegate</span>);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> TDelegate CreateDelegate&lt;TDelegate&gt;(MethodBase method,
        Func&lt;Type[], ParameterExpression[], MethodCallExpression&gt; getCallExpression)
    {
        var parameterExpressions = ExtractParameterExpressionsFrom&lt;TDelegate&gt;();
        CheckParameterCountsAreEqual(parameterExpressions, method.GetParameters());

        var call = getCallExpression(GetTypeArgumentsFor(method), parameterExpressions);

        var lambda = Expression.Lambda&lt;TDelegate&gt;(call, parameterExpressions);
        <span class="kwrd">return</span> lambda.Compile();
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ParameterExpression[] ExtractParameterExpressionsFrom&lt;TDelegate&gt;()
    {
        <span class="kwrd">return</span> <span class="kwrd">typeof</span>(TDelegate)
            .GetMethod(<span class="str">&quot;Invoke&quot;</span>)
            .GetParameters()
            .ToParameterExpressions()
            .ToArray();
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> CheckParameterCountsAreEqual(
        IEnumerable&lt;ParameterExpression&gt; delegateParameters,
        IEnumerable&lt;ParameterInfo&gt; methodParameters)
    {
        <span class="kwrd">if</span>(delegateParameters.Count() != methodParameters.Count())
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;The number of parameters of the requested delegate does not match &quot;</span> +
                <span class="str">&quot;the number parameters of the specified method.&quot;</span>);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> Type[] GetTypeArgumentsFor(MethodBase method)
    {
        var typeArguments = method.GetGenericArguments();
        <span class="kwrd">return</span> (typeArguments.Length &gt; 0) ? typeArguments : <span class="kwrd">null</span>;
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> Expression[] ProvideStrongArgumentsFor(
        MethodInfo method, ParameterExpression[] parameterExpressions)
    {
        <span class="kwrd">return</span> method.GetParameters()
            .Select((parameter, index) =&gt;
                Expression.Convert(parameterExpressions[index],
                                   parameter.ParameterType))
            .ToArray();
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> ConcurrentDictionary&lt;Type, Object&gt; _delegateCache =
        <span class="kwrd">new</span> ConcurrentDictionary&lt;Type, Object&gt;();
}</pre>
<p>I actually provided two <em>CreateDelegate</em> methods here, one for instance methods (the first one) and one for static methods ( the second one). The created delegates are cached in a dictionary because the call of <em>lambda.Compile()</em> seems to be quite expensive. </p>
<p>Now I have to warn you that, based on first preliminary measurements, this implementation probably isn’t going to outperform&#160; Delegate.CreateDelegate(). In fact, if you’re interested have a look at <a href="http://kohari.org/2009/03/06/fast-late-bound-invocation-with-expression-trees/">this approach</a> first as it seems much faster. I added some spike code to the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Spikes/DynamicMethodInvocationSpike">Elegant Code repository</a> for those who fancy to take a look.&#160;&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/07/30/createdelegatet-an-exercise-in-using-expressions/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Enter a Parallel Universe Using IKVM.NET</title>
		<link>http://elegantcode.com/2010/06/25/enter-a-parallel-universe-using-ikvm-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=enter-a-parallel-universe-using-ikvm-net</link>
		<comments>http://elegantcode.com/2010/06/25/enter-a-parallel-universe-using-ikvm-net/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 23:20:27 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/06/25/enter-a-parallel-universe-using-ikvm-net/</guid>
		<description><![CDATA[IKVM.NET is something I’ve been playing with for a while now, but seeing this awesome trailer today reminded me that I should write a post about it. I always considered Java to be some kind of parallel universe compared to .NET where a lot of interesting lessons can be learned. I never did any serious [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ikvm.net/index.html">IKVM.NET</a> is something I’ve been playing with for a while now, but seeing <a href="http://jz10.java.no/java-4-ever-trailer.html">this awesome trailer</a> today reminded me that I should write a post about it. </p>
<p>I always considered Java to be some kind of parallel universe compared to .NET where a lot of interesting lessons can be learned. I never did any serious Java development throughout my professional career, but I like to follow up on the trends in the Java community. Although the Java community suffers from some of the same diseases as the .NET community, the wide-spread acceptance of open-source and the adoption of new, fascinating languages on top of the JVM is an interesting evolution that I feel is lacking in the .NET world. Although the CLR/DLR is probably better designed to host a wider diversity of programming languages than the JVM, the rise of programming languages like <a href="http://www.scala-lang.org/">Scala</a>, <a href="http://clojure.org/">Clojure</a>, <a href="http://groovy.codehaus.org/">Groovy</a> and others is more sparse in the Java universe. Some of the most useful open-source projects in .NET today&#160; initially started out by porting the code of established Java libraries, like NUnit, NHibernate and Spring.NET, etc. …. Anyway, we’re wandering off.</p>
<p>Did you ever need to interoperate with a Java library while developing .NET applications? I have to admit, it doesn’t come up very often but when it does (especially when using IBM products <img src='http://elegantcode.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ), IKVM.NET might save you from a whole lot of trouble. </p>
<p>With IKVM.NET its possible to use Java API’s from a .NET application or even to use the Java language to develop .NET applications. Let me show you a quick example.</p>
<p>Say for example that you’re done with the DateTime class in .NET and you need a library that gives you more power in dealing with dates and time in your .NET applications. You do a little searching on the web and there it is, a full blown API like <a href="http://joda-time.sourceforge.net/">Joda Time</a> (I’m well aware that honorable <a href="http://msmvps.com/blogs/jon_skeet/">Jon Skeet</a> has <a href="http://code.google.com/p/noda-time/">ported this framework to .NET</a> already, but bear with me).</p>
<p>All we have to do to start using Joda Time in a .NET application is to download <em>joda-time.jar</em> and feed it to the <em>ikvmc.exe</em> command-line tool that comes with the binaries of IKVM.NET. Out comes a full blown .NET assembly by executing the following command:</p>
<blockquote><p>ikvmc -target:library joda-time-1.6.jar</p>
</blockquote>
<p>There are a whole slew of other options that you can specify here, like signing the resulting assembly (who still does that, really), specifying the assembly version, etc. …</p>
<p>This is how the generated assembly looks like in Reflector.</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/06/Reflector.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="Reflector" border="0" alt="Reflector" src="http://elegantcode.com/wp-content/uploads/2010/06/Reflector_thumb.jpg" width="240" height="210" /></a> </p>
<p>The following block of code is small utility that I developed to deal with the time zone arithmetic for the <a href="http://europevan.blogspot.com/">Europe Virtual ALT.NET</a>. </p>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Windows.Forms;
<span class="kwrd">using</span> org.joda.time;
<span class="kwrd">using</span> org.joda.time.format;
<span class="kwrd">using</span> DateTime = org.joda.time.DateTime;
<span class="kwrd">using</span> TimeZone = java.util.TimeZone;

<span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> Main : Form
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String London = <span class="str">&quot;Europe/London&quot;</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> String Brussels = <span class="str">&quot;Europe/Brussels&quot;</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EST = <span class="str">&quot;EST&quot;</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> String MST = <span class="str">&quot;MST&quot;</span>;
    <span class="kwrd">private</span> <span class="kwrd">const</span> String PST = <span class="str">&quot;PST&quot;</span>;

    <span class="kwrd">public</span> Main()
    {
        InitializeComponent();
        DateTimeTextBox.Text = CurrentDateAndTime();
    }

    <span class="kwrd">private</span> <span class="kwrd">void</span> ConvertButton_Click(Object sender, EventArgs e)
    {
        var dateTime = <span class="kwrd">new</span> DateTime(DateTimeTextBox.Text, DateTimeZone.UTC);

        var london = ConvertToTimeZone(London, dateTime);
        var brussels = ConvertToTimeZone(Brussels, dateTime);
        var est = ConvertToTimeZone(EST, dateTime);
        var mst = ConvertToTimeZone(MST, dateTime);
        var pst = ConvertToTimeZone(PST, dateTime);

        var formatter = BuildDateTimeFormatter();

        ResultTextBox.Text = String.Format(
            <span class="str">&quot;{0} UK, {1} Brussels, {2} EST, {3} MST and {4} PST.&quot;</span>,
            london.toString(formatter),
            brussels.toString(formatter),
            est.toString(formatter),
            mst.toString(formatter),
            pst.toString(formatter));
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> String CurrentDateAndTime()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> DateTime(DateTimeZone.UTC).ToString();
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> DateTime ConvertToTimeZone(String timeZone, DateTime dateTime)
    {
        var targetTimeZone = DateTimeZone
            .forTimeZone(TimeZone.getTimeZone(timeZone));
        <span class="kwrd">return</span> dateTime.toDateTime(targetTimeZone);
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> DateTimeFormatter BuildDateTimeFormatter()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> DateTimeFormatterBuilder()
            .appendHourOfHalfday(2)
            .appendLiteral(<span class="str">&quot;:&quot;</span>)
            .appendMinuteOfHour(2)
            .appendLiteral(<span class="str">&quot; &quot;</span>)
            .appendHalfdayOfDayText()
            .toFormatter();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>The distribution of IKVM.NET also comes with .NET implementation of a whole slew of Java class libraries that you can directly use in a .NET application whenever needed.</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/06/IKVM.jpg"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="IKVM" border="0" alt="IKVM" src="http://elegantcode.com/wp-content/uploads/2010/06/IKVM_thumb.jpg" width="400" height="377" /></a> </p>
<p>But remember, as with all things that seem too good to be true, there are a couple of major downsides as well. The one that you run into fairly quickly is generics. I tried generating a .NET assembly from <a href="http://code.google.com/p/make-it-easy/">Make It Easy</a> the other day and I noticed that some of the types in the resulting assembly where plain classes while they were defined as generics in the original JAR file. The explanation that I found was that Java checks generics only at compile time and not at runtime. In .NET generics are provided at runtime. If the generics from Java would convert to .NET, then every Java compiler warning would produce a runtime error. All the old code would not run. There is many old code in the Java VM itself. </p>
<p>The <a href="http://weblog.ikvm.net/">IKVM.NET blog</a> is a great resource for some of the other interoperability issues you might experience. Maybe this will come in handy someday, who knows?</p>
<p>Till next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/06/25/enter-a-parallel-universe-using-ikvm-net/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Prefer Additional Methods Over Additional Overloads</title>
		<link>http://elegantcode.com/2010/06/20/prefer-additional-methods-over-additional-overloads/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=prefer-additional-methods-over-additional-overloads</link>
		<comments>http://elegantcode.com/2010/06/20/prefer-additional-methods-over-additional-overloads/#comments</comments>
		<pubDate>Sun, 20 Jun 2010 17:35:54 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Craftsmanship]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/06/20/prefer-additional-methods-over-additional-overloads/</guid>
		<description><![CDATA[If you have ever written code that is going to be used as an API for other programmers, you may start to think about writing code in a different viewpoint from what you normally do. Most of us write code for the purpose of achieving a goal.&#160; If we practice writing elegant code, we are [...]]]></description>
			<content:encoded><![CDATA[<p>If you have ever written code that is going to be used as an API for other programmers, you may start to think about writing code in a different viewpoint from what you normally do.</p>
<p>Most of us write code for the purpose of achieving a goal.&#160; If we practice writing elegant code, we are conscious of making that code as readable and terse as possible.</p>
<p><strong>Seldom do we think about the use of our code from an API standpoint.</strong></p>
<p>There is a subtle difference between designing your code in a way that will make it easier for someone else to maintain, and designing your code in a way that will make it easier for someone else to use.</p>
<h2>Intellisenselessness</h2>
<p>How often are you working against some API and you type a method name you want to use only to have intellisense present you with 5 overloads for the method all with several different parameters choices?</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/06/LoginOverloads.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="LoginOverloads" border="0" alt="LoginOverloads" src="http://elegantcode.com/wp-content/uploads/2010/06/LoginOverloads_thumb.png" width="600" height="151" /></a> </p>
<p>Which one do you use?&#160; It is hard to be sure, you end up having to read through the long lists of parameters to figure out what method you should call and what parameters you should pass it.</p>
<p>Wouldn’t it be better if you were presented with what the method does in the method name rather than guessing what it does in the parameter list?&#160; Something like this?</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/06/LoginMoreMethods.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="LoginMoreMethods" border="0" alt="LoginMoreMethods" src="http://elegantcode.com/wp-content/uploads/2010/06/LoginMoreMethods_thumb.png" width="596" height="261" /></a> </p>
<h2>Perspective</h2>
<p>From the perspective of the person writing the <em>Login</em> method(s), overloads probably seem like the most efficient and correct way to implement the multiple ways the method can be called.</p>
<p>From the perspective of the person using the <em>Login</em> method(s), additional methods are much preferred, because they are easier to understand and know what you are looking for.</p>
<p><strong>Try to think from the perspective of someone using your code when writing your code.</strong></p>
<h2>Extract boolean parameter to two methods</h2>
<p>I want to take a look at a very specific example that can be of great benefit to the readability and use of your code.</p>
<p>Take a look at this code below.</p>
<div id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Login()</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span> }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Login(<span style="color: #0000ff">bool</span> rememberMe)</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Seems like a fine overload of a <em>Login</em> method.&#160; I have written code just like this, you probably have also.&#160; </p>
<p>&#160;</p>
<p>Unfortunately, by adding this overload, we have added some complexity to our API, because now the user of that code has to see that there is an additional overload that take a bool parameter called <em>rememberMe</em>.</p>
<p>Consider this longer alternative.</p>
<div id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> LoginRememberMe()</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum2">   2:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum3">   3:</span> }</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum4">   4:</span>&#160; </pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum5">   5:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> LoginDoNotRememberMe()</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum6">   6:</span> {</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"><span style="color: #606060" id="lnum7">   7:</span> }</pre>
<p><!--CRLF--></div>
</div>
<p>Instead of overloading <em>Login</em> and making the user have to decide which overload to call and pass in a parameter, we have elected to create two differently named methods which take 0 parameters and clearly state what they are going to do.</p>
<p>I’m not saying you should never write overloads, but anytime you see an overload in your code base, you should stop and think if it would be more clear to make that overloaded method into two different methods that can eliminate one or more of the parameters.</p>
<p><strong>Any time you are restricting the number of choices someone using your code has to make, you are making that code simpler to use.</strong></p>
<p>If you don’t believe me, consider why the iPhone has only one button.</p>
<h5><strong>As always, you can subscribe to this </strong><a href="http://feeds2.feedburner.com/ElegantCode"><strong>RSS feed</strong></a><strong> to follow my posts on elegant code.&#160; Feel free to check out my main personal blog at </strong><a href="http://simpleprogrammer.com"><strong>http://simpleprogrammer.com</strong></a><strong>, which has a wider range of posts, updated 2-3 times a week.&#160; Also, you can follow me on twitter </strong><a href="http://twitter.com/jsonmez"><strong>here</strong></a><strong>.</strong></h5>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/06/20/prefer-additional-methods-over-additional-overloads/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>The Power of Enum</title>
		<link>http://elegantcode.com/2010/05/08/the-power-of-enum/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-power-of-enum</link>
		<comments>http://elegantcode.com/2010/05/08/the-power-of-enum/#comments</comments>
		<pubDate>Sat, 08 May 2010 18:58:25 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/08/the-power-of-enum/</guid>
		<description><![CDATA[One of the most overlooked tools in modern programming languages for producing elegant code is the enumeration. The enumeration is such a simple concept, yet it yields such a high return in both readability and usability of your code. The enum is able to eliminate the need for XML style comments for a parameter to [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most overlooked tools in modern programming languages for producing elegant code is the enumeration.</p>
<p>The enumeration is such a simple concept, yet it yields such a high return in both readability and usability of your code.</p>
<p>The <em>enum</em> is able to <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">eliminate the need for XML style comments</a> for a parameter to a method, and <a href="http://elegantcode.com/2010/05/01/say-no-to-null/">prevent the passing of null</a> in one fell swoop.</p>
<ul>
<li>Enumerations make the set of choices for a parameter finite and self-describing.</li>
<li>Enumerations which are parameters can never be set to null.</li>
</ul>
<ul>
<h2>Explicit documentation becomes self-documentation</h2>
</ul>
<p>Let’s look at an example, so I can show you what I am talking about:</p>
<pre class="csharpcode">
<span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Causes pacman to eat the specified fruit.</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="rem">/// &lt;param name="fruit"&gt;A fruit which must either be an apple, banana, orange, or</span>

<span class="rem">/// cherries.&lt;/param&gt;</span>
<span class="kwrd">public</span> <span class="kwrd">void</span> Eat(<span class="kwrd">string</span> fruit)
{
    <span class="kwrd">switch</span>(fruit)
    {
        <span class="kwrd">case</span> <span class="str">"apple"</span>:
            Console.WriteLine(<span class="str">"Ate an apple"</span>);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> <span class="str">"banana"</span>:
            Console.WriteLine(<span class="str">"I love bananas"</span>);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> <span class="str">"orange"</span>:
            Console.WriteLine(<span class="str">"A color and a fruit"</span>);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> <span class="str">"cherries"</span>:
            Console.WriteLine(<span class="str">"This one is plural"</span>);
            <span class="kwrd">break</span>;
        <span class="kwrd">default</span>:
            <span class="kwrd">break</span>;
    }
}</pre>
<p><!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<p>You can see here that we need some comment to tell the user of the method what can be passed into the fruit parameter.</p>
<p>We have to handle the default case, in case someone is able to pass in something we didn’t expect.</p>
<p>A simple typo in calling the method or in our method, could result in a difficult to find bug.</p>
<p>Someone can call this method with null like so:</p>
<pre class="csharpcode"><span class="rem">// passing in null is allowed, strings can be null, objects can always be null.</span>
Eat(<span class="kwrd">null</span>);</pre>
<p><!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<p>Now take a look at the example that uses an enumeration for fruits.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Eat(Fruits fruit)
{
    <span class="kwrd">switch</span> (fruit)
    {
        <span class="kwrd">case</span> Fruits.Apple:
            Console.WriteLine(<span class="str">"Ate an apple"</span>);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> Fruits.Banana:
            Console.WriteLine(<span class="str">"I love bananas"</span>);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> Fruits.Orange:
            Console.WriteLine(<span class="str">"A color and a fruit"</span>);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> Fruits.Cherries:
            Console.WriteLine(<span class="str">"This one is plural"</span>);
            <span class="kwrd">break</span>;
    }
}</pre>
<p><!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<p>Do we really need the XML comment anymore?  When you try to call Eat() you will immediately see that it requires a Fruit and when you type “Fruit.” you will get:</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/05/SS20100508_11.49.39.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="SS-2010-05-08_11.49.39" src="http://elegantcode.com/wp-content/uploads/2010/05/SS20100508_11.49.39_thumb.png" border="0" alt="SS-2010-05-08_11.49.39" width="163" height="112" /></a></p>
<p>Pretty self-explanatory.</p>
<p>Consider what happens when I try to pass null into the method.</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/05/SS20100508_11.51.22.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="SS-2010-05-08_11.51.22" src="http://elegantcode.com/wp-content/uploads/2010/05/SS20100508_11.51.22_thumb.png" border="0" alt="SS-2010-05-08_11.51.22" width="460" height="59" /></a></p>
<p>You cannot do it.  No matter how hard you try.</p>
<p><em><strong>Side note:</strong> before the comments start coming in.  The example above is using a switch statement so that it can be simple for demonstration.  In real code you would want to do something smarter here like use a Dictionary&lt;Fruits, string&gt; and replace the switch.</em></p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/05/choices760701.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="choices-760701" src="http://elegantcode.com/wp-content/uploads/2010/05/choices760701_thumb.jpg" border="0" alt="choices-760701" width="544" height="465" /></a></p>
<h2>The power of limiting choices</h2>
<p>It is a funny kind of a seeming contradiction that limiting the amount of choices increases the effectiveness of something.</p>
<p>The real power of enumerations to make your code more elegant lies in this contradiction.  By constraining the choices of what can be passed into a method, it becomes possible to list those choices out.  Which allows intellisense to display the choices for you.  You are forcing the IDE to document your code automatically.</p>
<p>Options that are self-discoverable are always going to be easier to use and understand, because they don’t require the mind to parse a human sentence and translate it into code.</p>
<p>Limiting choices protects your code in many other ways.  You prevent typos on either end because the compiler will now tell you if you have typed one of the choices wrong.</p>
<p>Testing becomes simpler, because the choices are finite.  Edge conditions and testing invalid input don’t apply to methods that take enumerations.  All input possibilities are known.</p>
<h2>When to use enumerations</h2>
<p>It is more often than you would think.  Let me show you an example where many people might not notice they could use an <em>enum</em>:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> StartGame(<span class="kwrd">int</span> numberOfPlayers);</pre>
<p>Many programmers would look at this code and not even think about using an enumeration here.  The number of players feels like an integer.</p>
<p><strong>Every time you are writing a method and declaring the parameters, you should be asking yourself “How can I constrain the choices of what can be passed in?”</strong></p>
<p>In this case, it is very simple.  How many players does the game allow?  There might even be a constant MAX_PLAYERS = 4.</p>
<p>We can very easily convert this code to use a simple <em>enum</em> and constrain the choices.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> StartGame(PlayerCountSelection numberOfPlayers);</pre>
<p>This small change may not seem like much, but it is going to immediately eliminate the need for writing unit tests to check for invalid player amounts being passed in, and it is going to prevent another programmer using this method from having to look in the documentation to find out the valid ranges of the <em>int</em>.</p>
<p>It is the culmination of limiting choices throughout your code that produces a net effect of reducing the complexity of the system.  It is the same with most of the best practices I suggest on this blog.</p>
<p>So when should you use enumerations?  Any time you can.  Any time you have the opportunity to constrain input choices, do it.</p>
<p>Combine them with maps and function pointers for the <a href="http://simpleprogrammer.com/2010/02/25/super-combo-map-function-pointer/">ultimate combo</a>!</p>
<h6>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h6>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/08/the-power-of-enum/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Say &#8220;No&#8221; to &#8220;Null&#8221;</title>
		<link>http://elegantcode.com/2010/05/01/say-no-to-null/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=say-no-to-null</link>
		<comments>http://elegantcode.com/2010/05/01/say-no-to-null/#comments</comments>
		<pubDate>Sat, 01 May 2010 19:35:05 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Conventions]]></category>
		<category><![CDATA[Craftsmanship]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/01/say-no-to-null/</guid>
		<description><![CDATA[I was recently asked to write a fairly simple piece of code.  In this simple piece of code, I didn’t handle a null input.  I was asked about what kinds of things I would consider about the input, and I pretty much knew what the asker was going after. What do you do if &#8220;null” [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently asked to write a fairly simple piece of code.  In this simple piece of code, I didn’t handle a null input.  I was asked about what kinds of things I would consider about the input, and I pretty much knew what the asker was going after.</p>
<blockquote><p>What do you do if &#8220;null” is passed in?</p></blockquote>
<p>My answer may turn out to be a bit of a surprise.</p>
<blockquote><p><span style="background-color: #f4f5f7;">Nothing, I don’t handle nulls in code that I control the use of.</span></p></blockquote>
<p>“What?  What?” you say.  “You don’t handle null?  What kind of heresy is that?”  It is the kind of heresy that helps produce elegant code and I will show you why.</p>
<h2>How well do you handle null right now?</h2>
<p>Would you say that in most of the code you write you properly check all arguments for null?</p>
<p>Or, do you like most developers, handle null in certain cases when you happen to think about it, or after the application dumps a “null pointer exception” stack trace?</p>
<p>Be honest, look at your code if you have to.</p>
<p>The problem is “d00d ur d0ing it r0ng!”</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2010/05/johnmccarthyprogrammingcompletelywrong.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="john-mccarthy-programming-completely-wrong" src="http://elegantcode.com/wp-content/uploads/2010/05/johnmccarthyprogrammingcompletelywrong_thumb.jpg" border="0" alt="john-mccarthy-programming-completely-wrong" width="349" height="452" /></a></p>
<p>Unless you are some kind of anal retentive perfectionist, you are probably not handling null in every single method call.  That means there are huge potential bugs in the code that you are writing which will throw null pointer exceptions.  That is bad, I agree.</p>
<p>So, if you are not handling it correctly right now, then what can you do to fix that?</p>
<h2>Avoiding null in the code you “own”</h2>
<p>You can’t control external libraries.  And you can’t control how people will use your code, but you can control the code you write and you can, to a degree, control the code your shop writes.</p>
<p>The better strategy is to never pass null in the first place.</p>
<p>You can either focus your efforts on:</p>
<ul>
<li>Checking for null</li>
<li>Not ever passing null</li>
</ul>
<ul>The more elegant solution is to focus on never passing null.  By doing this you will end up writing less code and avoid decisions about how to handle null inside of a method that doesn’t have enough context to decide what to do.</ul>
<p>Let’s look at an example:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">string</span> TransmographyThreeStrings(<span class="kwrd">string</span> first, <span class="kwrd">string</span> second, <span class="kwrd">string</span> third)
{
     <span class="kwrd">if</span>(<span class="kwrd">string</span>.isNull(first) || <span class="kwrd">string</span>.isNull(second) || <span class="kwrd">string</span>.isNull(third))
    {
           <span class="rem">// hmm, I donno, what should I do?  Should I throw an exception?</span>
           <span class="rem">// should I return an empty string?</span>
           <span class="rem">// what if the first string wasn't null, can we still do something meaningful?</span>
           <span class="rem">// how will the caller of the method know what I will do?</span>
    }

}</pre>
<p>You can see there that we are checking each parameter for null.  The problem is we don’t know what we should do.  We have lots of options, but none of them are obvious.</p>
<p>How much better is it to make sure that we never pass null into methods, rather than write this kind of code in every method?</p>
<h2>What about accidentally passing in null?</h2>
<p>Many of you are probably thinking at this point that the main way null gets passed into a method is because someone calls a method without knowing that it contains a null value.</p>
<pre class="csharpcode">TransmographyThreeStrings(<span class="str">"Hello"</span>, <span class="str">"World"</span>, mysteryObject.Text);</pre>
<p>Perhaps <em>mysteryObject.Text </em>is null.  You wouldn’t even know it.</p>
<p>Ah, but you can.  Or you can prevent it at least.  Somewhere <em>mysteryObject </em>gets created.  When it gets created its values either get initialized or not.  You can prevent any of its values from being null, several ways:</p>
<ul>
<li>Always initialize variables when they are declared.</li>
<li>Use a <a href="http://en.wikipedia.org/wiki/Builder_pattern">builder pattern</a> to ensure that objects are always fully constructed before being created.</li>
<li>Use properties to provide default values or lazy initialize.</li>
<li>Make your objects <a href="http://en.wikipedia.org/wiki/Immutable_object">immutable</a> as much as possible.</li>
</ul>
<p>The practices that prevent null from accidentally being passed in make your code much more elegant than repeating <em>if blah == null</em> code all over the place.</p>
<p><strong>In general, you should always strive to eliminate the passing of null rather than checking for null.  By doing so you reduce extra lines of code in each method, and are forced to use better design practices.</strong></p>
<h2>Exceptions</h2>
<p>Yes, there are times when you need to check for null.  If you are writing a library that external developers will use, then you will probably want to check for null in all of your methods that are exposed as part of the API.  (On your internal methods, you don’t need to since you have already cleansed the input.)</p>
<p>Also, if your code is being used as a callback to some API and you don’t know if it can ever pass null into your code, you probably should check for null.</p>
<p>A bad excuse is that other developers may pass null to your method. <strong>It is much better as a software shop to put the onus of not passing null on the caller of any method rather than putting it on the writer of the method being called.</strong></p>
<p>You will also reduce your exception handling code, because you will have less exceptions for invalid parameters.</p>
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/01/say-no-to-null/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
	</channel>
</rss>

