<?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>NOthingyoumissed &#187; c#</title>
	<atom:link href="http://georgemauer.net/blog/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://georgemauer.net/blog</link>
	<description>George Mauer is on the net</description>
	<lastBuildDate>Sat, 15 May 2010 16:13:40 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Hey, I Think I&#8217;ve Invented a New Pattern</title>
		<link>http://georgemauer.net/blog/hey-i-think-ive-invented-a-new-pattern/</link>
		<comments>http://georgemauer.net/blog/hey-i-think-ive-invented-a-new-pattern/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 07:58:12 +0000</pubDate>
		<dc:creator>togakangaroo</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://georgemauer.net/blog/?p=119</guid>
		<description><![CDATA[Ok maybe not totally new, I am sure that its just a projection of something I once noticed subcionscioiusly in a F# project. But in the C# space, I&#8217;ve yet to see something quite like it.  
The problem is that programs are complicated.  I don&#8217;t tend to help the issue.  In a [...]]]></description>
			<content:encoded><![CDATA[<p>Ok maybe not totally new, I am sure that its just a projection of something I once noticed subcionscioiusly in a F# project. But in the C# space, I&#8217;ve yet to see something quite like it.  </p>
<p>The problem is that programs are complicated.  I don&#8217;t tend to help the issue.  In a flash I don&#8217;t hesitate to layer on additional complexity with domain models, frameworks, and complex infrastructures.  Entities, sevices, repositories and aggregate roots &#8211; they&#8217;re the tools that we reach for all too often.  That is not to say that Domain Driven Design is a poor paradigm &#8211; I&#8217;m a big fan &#8211; it&#8217;s just not always necessary.</p>
<p>Take for example a typical scenario. You are given an integer which uniquely identifies a customer and are asked to generate a report of all their orders, export it to a pdf file and return as a Stream.  My first impulse is to start with the customer and order objects, identify the bounded context, figure out the aggregate roots, start writing data access mapping code, and so on.  If I&#8217;m lucky, I only do this for a few hours before hearing the voice of an incorporeal Ted Neward yelling at me to <strong>STOP</strong>.  I was not asked to build a domain model, I do not need to keep track of state, there is no validation, or (much) business logic.  The problems that DDD is intended to solve are simply not present here.  I need to do one thing and one thing only, map an integer to a Stream!  </p>
<p>And yes, I do realize that this is exactly what the CQRS guys have been harping on for years.</p>
<p>My Solution:</p>
<p>Each of my last few projects has contained a very simple interface.</p>
<pre name="code" class="c-sharp">
public IMapper&lt;INPUT_TYPE, OUTPUT_TYPE&gt; {
  OUTPUT_TYPE Map(INPUT_TYPE obj);
}
</pre>
<p>Get it? Put in an integer, get back a Stream, what could be simpler?  Ok, maybe that&#8217;s too simple.  Any change at all would require modifying the implementation.  This is all that icky procedural programming stuff.  What about reusability, encapsulation, separation of concerns, and our other OO goodies?   Fortunately, we don&#8217;t have to give these up.  All we have to do is introduce a couple of obvious seams.  We no longer transform an integer directly to a Stream.  Instead we:</p>
<ol>
<li>Take the id and map it to a DataSet that contains the report data.</li>
<li>Map a DataSet to the appropriate fully built Crystal Reports ReportDocument.</li>
<li>Map a ReportDocument to a MemoryStream of a pdf file.</li>
</ol>
<pre name="code" class="c-sharp">
IMapper&lt;int, DataSet&gt; _dataProvider;
IMapper&lt;DataSet, ReportDocument&gt; _reportGenerator;
IMapper&lt;ReportDocument, Stream&gt; _pdfReportExporter;

public Stream GetCustomerReport(int customerId) {
  return _pdfReportExporter.Map(
           _reportGenerator.Map(
             _dataProvider.Map(customerId)));
}
</pre>
<p>Pretty nice huh?   Well not that nice.  If you&#8217;re a naming perfectionist like I this should make you shiver.  When it comes to maintainability, good intention-revealing namespace, class, and method names are worth a million unit tests and n-tier architectures.  Forget requirements docs and self-documenting code, proper naming is the number one tool for communicating our intent.</p>
<p>I lecture my team on this constantly and yet I allow myself the use of the the term &#8220;Map&#8221;?!  A generic term that could indicate anything except (unless you&#8217;re a cartographer) a concept from your ubiquitous langauge.  I should be ashamed.</p>
<p>We want to keep our generic IMapper interface though, it&#8217;s so slick, allows us to write minimal code and you you could easily imagine it coming in handy.  For example, perhaps as the domain itself becomes more complicated, it becomes useful to break our IMapper&lt;int, DataSet&gt; down further.<br />
 1. The integer is get mapped to a Customer entity.<br />
 2. This gets mapped to a ReportSpecification.<br />
 3. The ReportSpecification is evaluated and mapped to a StoredProcedureInvocation<br />
 4. The procedure is executed and finally returns our DataSet. </p>
<p>You could imagine all sorts of neat little tricks you could play with our IoC container &#8211; we could have it automatically link transforms together or subsitute out implemenations.  Simply by knowing that all these components transform one object to another we could configure automatic caching, deferred execution proxies, and so on.  All things that are made far easier because all transformations are achieved via IMapper.Map.</p>
<p>What we really need is a way to introduce aliases for the Map() method.  Preferably ones that depend on the input and output type.  So why sit there scratching our heads?  C# is a flexible enough language, let&#8217;s just let&#8217;s do that thing that I just said.</p>
<pre name="code" class="c-sharp">
public CustomerOrderReportGenerator : IMapper&lt;DataSet, ReportDocument&gt; {
  public ReportDocument Map(DataSet data) {
    // implementation
  }
}
public partial static class AliasExtensions {
  public static ReportDocument GenerateReportFrom(this IMapper&lt;ReportDocument, DataSet&gt; mapper, DataSet ds) {
    return mapper.Map(ds); }
}
</pre>
<p>And now we have aliases:</p>
<pre name="code" class="c-sharp">
  _pdfReportExporter.Export(
    _reportGenerator.GenerateReportFrom(
      _dataProvider.GetOrderDataFor(customerId)));
</pre>
<p>The poor readability of this bothers me.  The LISPers among us might not mind reading backwards through a stack of nested parentheses but as a fan of fluent interfaces I&#8217;d like to see my code read as close to natural english as possible.  </p>
<p>Same trick, now featuring double dispatch!</p>
<pre name="code" class="c-sharp">
public partial static class AliasExtensions {
  public static ReportDocument ComposeIntoReportUsing(this DataSet ds, IMapper&lt;ReportDocument, DataSet&gt; mapper) {
    return mapper.Map(ds); }
}
</pre>
<p>Allows us to do:</p>
<pre name="code" class="c-sharp">
  return _dataProvider
    .GetOrderDataFor(customerId)
    .ComposeIntoReportUsing(_reportGenerator)
    .ToStreamUsing(_pdfReportExporter);
</pre>
<p>And there you have it.  Nice, fluent, and composable. </p>
<p>What do you guys think?  <b>Aliased Maps</b> a good name?</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgeorgemauer.net%2fblog%2fhey-i-think-ive-invented-a-new-pattern%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgeorgemauer.net%2fblog%2fhey-i-think-ive-invented-a-new-pattern%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://georgemauer.net/blog/hey-i-think-ive-invented-a-new-pattern/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Error Handling and the Message Repackaging Anti-Pattern</title>
		<link>http://georgemauer.net/blog/error-handling-and-the-message-repackaging-anti-pattern/</link>
		<comments>http://georgemauer.net/blog/error-handling-and-the-message-repackaging-anti-pattern/#comments</comments>
		<pubDate>Fri, 16 Jan 2009 23:28:10 +0000</pubDate>
		<dc:creator>togakangaroo</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[exceptionhandling]]></category>
		<category><![CDATA[projectmanagement]]></category>

		<guid isPermaLink="false">http://nothingyoumissed.wordpress.com/?p=42</guid>
		<description><![CDATA[I currently have an interesting responsibility at work.  I am functioning as the manager and single-point-of-contact for a team in India working on imporving the codebase for one of our more important ASP.Net sites.  I know what you&#8217;re thinkin.  Did I say interesting?  I meant infuriating.  At the very least I should get a good [...]]]></description>
			<content:encoded><![CDATA[<p>I currently have an interesting responsibility at work.  I am functioning as the manager and single-point-of-contact for a team in India working on imporving the codebase for one of our more important ASP.Net sites.  I know what you&#8217;re thinkin.  Did I say interesting?  I meant infuriating.  At the very least I should get a good &#8220;Lessons Learned&#8221; post out of this.</p>
<p>Overall the experience hasn&#8217;t been too bad though.  I&#8217;ve been managing to maintain a decent rapport with their project manager and team lead, deadlines have been missed, but no more than I secretly expected, and overall they seem like fairly competent guys.  Their work isn&#8217;t innovative, Agile, testable, or well factored, but its decent enough.</p>
<p>Except for the exceptions.</p>
<p>Browsing one of their recent commits to our SVN lately (ok, so technically speaking they couldn&#8217;t figure out Subversion so they ftp-ed and <em>I</em> did the commit for them) I was shocked to discover the following <a href="http://en.wikipedia.org/wiki/Anti-pattern">error-handling anti-pattern</a> repeated <strong>41 </strong>times!</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode"><span class="kwrd">try</span> {
  <span class="rem">// Do Stuff</span>
}
<span class="kwrd">catch</span>(Exception ex) {
  <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(ex.Message);
}</pre>
<p>Do I get to name it?  Let&#8217;s call it the message repackaging anti-pattern.  And in case you&#8217;re not already reeling from this, the following is a mildly edited-down version of the letter I sent (Notice the eschewed profanity.  I believe a not insignificant achievement.)</p>
<hr />Dear Team,</p>
<div>
<div>While looking through some of your committed code I noticed quite a few (a quick search shows 41) places where you have code of the following form.</div>
<div>
<table border="0" cellspacing="0" cellpadding="3" width="100%">
<tbody>
<tr>
<td width="100%">
<pre><span>try</span><span style="font-size:x-small;"> {
 </span><span>// ...</span><span style="font-size:x-small;">
}
</span><span>catch</span><span style="font-size:x-small;">(Exception ex) {
 </span><span>throw</span><span style="font-size:x-small;"> </span><span>new</span><span style="font-size:x-small;"> Exception(ex.Message);
}</span></pre>
</td>
</tr>
</tbody>
</table>
</div>
<div>Let me be absolutely clear: This is the worst possible way of handling exceptions!</div>
<div>Let&#8217;s go over why:</div>
<div>
<ol>
<li><em>Not doing anything inside the exception.</em> If nothing happens within the catch block then what purpose does it serve? I have seen people prepare their code like this in anticipation of going back and adding logging at some later date. Although this is not necessarily the best logging solution, it is acceptable when you actually implement the code! However, preparing your method like this in anticipation of some future date does nothing but make the code difficult to read. It&#8217;s not like it is that hard to go back later and add a try&#8230;catch block; if you&#8217;re using a refactoring tool like CodeRush it is literally four keystrokes. </li>
<li><em>Catching the base Exception.</em> Not every exception can have something be done about it. The canonical example is an OutOfMemoryException or one implying the database might be down. Is there anything to do in this case other than drop the user to an error page? I would even go so far as to say that most exceptions fall in this category &#8211; you just can&#8217;t do anything about them.  I strongly encourage you to read <a title="Stop Catching Exceptions" rel="nofollow" href="http://gen5.info/q/2008/07/31/stop-catching-exceptions/">Stop Catching Exceptions</a> for a more in depth discussion.</li>
<li><em>Treating the message as if it were the most important thing</em>. Exceptions usually carry a heck of a lot more information than just their message. They carry their type and a StackTrace and a list of any inner exceptions. Many specializations of the Exception base have even more information specific to that type of error. Out of all that information, the message is arguably the <em>least</em> important &#8211; for debugging I would take a StackTrace over a message any day. But by creating an exception off of the message you are effectively stripping out all this useful stuff! If for some reason, you must create a new exception, at least use the constructor overload that includes the original error as an InnerException: new Exception(&#8221;I don&#8217;t know why I&#8217;m creating this&#8221;, ex);</li>
<li><em>Why create a new Exception object at all?</em> You already have a perfectly valid exception object. It is a simple matter to do:
<div>
<table border="0" cellspacing="0" cellpadding="3" width="100%">
<tbody>
<tr>
<td width="100%">
<pre><span>try</span><span style="font-size:x-small;"> {
 </span><span>// ...</span><span style="font-size:x-small;">
}
</span><span>catch</span><span style="font-size:x-small;">(Exception ex) {
 </span><span>// Log or otherwise handle the exception</span><span style="font-size:x-small;">
 </span><span>throw</span><span style="font-size:x-small;">; </span><span><span style="font-size:x-small;">// Same as throw ex;</span></span><span style="font-size:x-small;">
}</span></pre>
</td>
</tr>
</tbody>
</table>
</div>
</li>
</ol>
</div>
<div>So in conclusion</div>
<div>
<ul>
<li>Don&#8217;t catch an exception if you aren&#8217;t going to do anything with it.</li>
<li>Try to catch exceptions at the appropriate level and for the appropriate task. (logging inside private methods is probably unnecessary)</li>
<li>Do not create a new exception, throw the old one.</li>
</ul>
</div>
<div>Please take this as healthy constructive criticism. I hope that you agree with me on these points and that we can take care of this issue properly from now on.</div>
</div>
<p> </p>
<hr />A bit harsh perhaps, but I feel like for all the reasons above the immensity of this mistake cannot be overstated.  If you are doing this in your code STOP NOW and apologize to the maintenance gods!  You might even need to sacrifice a goat to appease them.  It&#8217;s that bad.</p>
<p>In any case, the recent commit has only 38 instances of this error.  So at least we&#8217;re getting better!</p>
]]></content:encoded>
			<wfw:commentRss>http://georgemauer.net/blog/error-handling-and-the-message-repackaging-anti-pattern/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
