<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>큰음량</title>
	
	<link>http://mobilecommerceonline.com/blog</link>
	<description>Turn It up To Eleven!</description>
	<lastBuildDate>Mon, 07 Sep 2009 19:20:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/mobilecommerceonline" /><feedburner:info uri="mobilecommerceonline" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Enumeration Maps (C#)</title>
		<link>http://feedproxy.google.com/~r/mobilecommerceonline/~3/H6e__CBastQ/</link>
		<comments>http://mobilecommerceonline.com/blog/?p=170#comments</comments>
		<pubDate>Mon, 07 Sep 2009 02:26:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[DotNet]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[Custom Attributes]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Enumerations]]></category>
		<category><![CDATA[Extensibility]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Maintainability]]></category>
		<category><![CDATA[Portability]]></category>

		<guid isPermaLink="false">http://mobilecommerceonline.com/blog/?p=170</guid>
		<description><![CDATA[As many who know me will attest, I am a big fan of type safety.  That might seem passé nowaday and I might risk seeming a little dated to say so, but I learned how to write code by reading such seminal works as Scott Meyers &#8220;Effective C++&#8221; et al.  The design guidelines [...]]]></description>
			<content:encoded><![CDATA[<p>As many who know me will attest, I am a big fan of type safety.  That might seem passé nowaday and I might risk seeming a little dated to say so, but I learned how to write code by reading such seminal works as Scott Meyers &#8220;Effective C++&#8221; et al.  The design guidelines carefully proscribed in this text and the others of similar ilk became something of commandments back in the day and one would run the risk of appearing gauche by committing a transgression against any of these rules.  Regarding downcasts, Meyers even draws parallels to biblical commandments by stating &#8220;Casts are to C++ programmers what the apple was to Eve&#8221;<sup>1</sup></p>
<p>The reason they are to be avoided in a type safe language like C++, C#, Java etc. is they become a maintenance nightmare.  This is because the developer who uses the downcast is really taking  on the work of the compiler.  Afterall, a primary reason we create object-oriented designs with virtual functions is to offload the work of figuring out what function to call onto the compiler and relieve the developer of this burden.  Downcasts undo that.</p>
<p>Now, what does all this talk about type safety have to do with mapping enumerations fields to values?  As it turns out, in C# enums can be considered types derived from their underlying representation.  That&#8217;s not <em>really</em> true, though.  Under the covers, all enumerations inherit from the pseudo (or special) class System.Enumeration.†  Enumerations are types which exist to enhance the maintainability of one&#8217;s code, to increase portability and to reduce the number of potential defects.  They exist as types so that the compiler can flag a problem if a developer should mistype the value of an string or number being used to make a decision.  Consider the following code:</p>
<pre name="code" class="c-sharp">if (databaseResponse == "SUCCESS") { /*Do something*/}</pre>
<p>Here, <em>databaseResponse</em> should only be allowed to contain a limited number of values, arguably no more than three:  undefined, success or failure.  Enumerations were created to ensure that the developer doesn&#8217;t inadvertently  mistype the string &#8220;SUCCESS&#8221; or to ensure that if the stringified value ever changes, the code should not have to change.  That&#8217;s why this code is better:</p>
<pre name="code" class="c-sharp">            enum DbResponse { Undefined, Success, Failure };
            /* ... */
            if (databaseResponse == DbResponse.Success) { /*Do Something*/}</pre>
<h3>The Problem With Enumerations</h3>
<p>The problem with using enumerations, however, has always been the fact that data returned from external sources, including databases, remote APIs and external files, must unmarshal the external representation of the enumerated value from a string or number into the enumerated type.</p>
<p>C# *is* able to take a string value and parse it to return the enumeration, but this is a very limited approach.  First, the string value must match the enumerated value.  Often times, the string values are defined by external organizations, including standards bodies that are little concerned about whether the string value can be coerced into a legitimate C# enumeration.</p>
<p>An example of this issue emegered while I was writing some code to deal with the <a href="http://www.census.gov/eos/www/naics/2007NAICS/2007_Definition_File.pdf">North American Industry Classification System</a>, which defines codes for various industries.  These codes are used to communicate the context of a credit transaction, so that a business rule might be applied to the transaction for determining whether or not the transaction is legitimate.  In this standard, each code has a name and an associated number.  &#8220;Bituminous Coal and Lignite Surface Mining&#8221; is an industry that is enumerated by the integer value 212111.  If one were to create a system by which the string &#8220;Bituminous Coal and Lignite Surface Mining&#8221; could be made into a text value, one might substitute the spaces for underscores and get &#8220;&#8221;Bituminous_Coal_and_Lignite_Surface_Mining&#8221; and write code using this value instead of the number 21211, which is not terribly descriptive.</p>
<pre name="code" class="c-sharp">enum Naic {Undefined, Bituminous_Coal_and_Lignite_Surface_Mining = 212111, /*...*/}
if (naic == Naic.Bituminous_Coal_and_Lignite_Surface_Mining) { /*...*/}</pre>
<p>This seems to work out alright until one comes to some of the other industry names like &#8220;Flower, Nursery Stock, and Florists&#8217; Supplies Merchant Wholesalers US&#8221;.  The issue here is that commas and apostrophes can&#8217;t be used to define an enumeration.  The thing that typically happens is that the developer comes up with some mapping from these real-world values to code.  In the process, information is lost, or worse, duplicate values are encountered.</p>
<p>The other problem not apparent in this particular example, is that the enumerations might not be enumerations of integer values like 212111.  Often times, the enumerated values are strings.  Let&#8217;s go back to the database stored procedure example for a moment.  It might be the case that one is tasked with maintaining a legacy applications that calls stored procedures which return more than one string representing success or failure.  As ghastly as this seems, it happens.  &#8220;Success&#8221;, rather than being represented by a boolean true, might instead be represented by numerous strings, which need to be parsed like &#8220;Ok&#8221;, &#8220;OK&#8221;, &#8220;Success: 03103&#8243;, &#8220;SUCCESS&#8221; or &#8220;YIPPEE!&#8221;.  Nevermind that this is an awful way to write stored procedures-  it&#8217;s legacy code and one must deal with it.  Alas, these values do not make for very good enumerations.  One cannot simply generated an instance of an enumeration from the responses and apply conditional logic:</p>
<pre name="code" class="c-sharp">DatabaseResponse dbResponse = (DatabaseResponse)(Enum.Parse(typeof(DatabaseResponse), callStoredProcedure()));</pre>
<p>The <em>DatabaseResponse</em> enum cannot define &#8220;Success: 03103&#8243; or &#8220;YIPPEE!&#8221;.  Both of those values contain characters that cannot be enumerated.  Also, there is a downcast here.  For the reasons that were already mentioned above, downcasts should be avoided.  The downcast exists because <em>Enum.Parse</em> cannot be made to return different types and is therefore restricted to returning objects.  This breaks the typesafety in the design.</p>
<p>Finally, the language definition of enumerations is broken with regard to how the language permits a single enumerated value to represent more than one numeric value.  It&#8217;s not that an enumeration shouldn&#8217;t be mapped to more than one numeric value, it&#8217;s that it&#8217;s defined very poorly indeed.  Simply relying on the mechanics of enumerations, one is able to map an enumerated field to more than one numeric value.  The following example uses the <em>Flags</em> attribute to allows the <em>destination </em>enumeration to contain more than one value.  When rules are applied, the other values can be filtered out by applying a bit-wise &#8220;&amp;&#8221; operation.</p>
<pre name="code" class="c-sharp">[Flags]
enum Destination
{
   Undefined = 0,
   Europe = 1,
   Africa = 2,
   America = 4
}
...
if ((destination &amp; Destination.Africa) == Destination.Africa) { /*...*/}</pre>
<p>This is just bad.  Nasty bad.  Here, in the modern age, one is expected to know the bit-wise representation of an enumerated value!  One is asked to apply binary arithmetic to enumerations to perform conditional checks!  Further, this &#8220;solution&#8221; only works for enumerations that have a very limited number of values, since the number of bits available will decrease rather rapidly.  Our NAIC example above certainly wouldn&#8217;t fit with its 440+ fields.</p>
<h3>A Solution, Please!</h3>
<p><br/><br />
<a href="http://mobilecommerceonline.com/blog/?page_id=127#solution">Click here to read more and see the solution!</a><br />
<br/></p>
<img src="http://feeds.feedburner.com/~r/mobilecommerceonline/~4/H6e__CBastQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://mobilecommerceonline.com/blog/?feed=rss2&amp;p=170</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://mobilecommerceonline.com/blog/?p=170</feedburner:origLink></item>
		<item>
		<title>A High-Performance Virtual Constructor (C#)</title>
		<link>http://feedproxy.google.com/~r/mobilecommerceonline/~3/LD_KBVBcGIw/</link>
		<comments>http://mobilecommerceonline.com/blog/?p=10#comments</comments>
		<pubDate>Sun, 16 Aug 2009 01:05:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[DotNet]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Extensibility]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Maintainability]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Portability]]></category>
		<category><![CDATA[Virtual Constructor]]></category>

		<guid isPermaLink="false">http://mobilecommerceonline.com/blog/?p=10</guid>
		<description><![CDATA[The virtual constructor is a factory design pattern that enables one to create an instance of a type that is not directly known to the compiled unit.  The virtual constructor&#8217;s build method returns a reference to the types base class or interface.  This pattern enhances an application&#8217;s maintainability by reducing the number of [...]]]></description>
			<content:encoded><![CDATA[<p>The virtual constructor is a factory design pattern that enables one to create an instance of a type that is not directly known to the compiled unit.  The virtual constructor&#8217;s build method returns a reference to the types base class or interface.  This pattern enhances an application&#8217;s maintainability by reducing the number of dependencies that the code unit has.  There are several straightforward ways to do this through reflection, both in .net and java.  Unfortunately, those techniques heavily on reflection in the runtime code path, which is slow and error-prone.  This post will demonstrate a technique for defining a generic virtual constructor that does not have this performance issue.</p>
<p>There are a couple situations where it is very useful to have such a virtual constructor:</p>
<ol>
<li> When you don’t want to hard-code an implementation type that may change, such as a 3rd party type that implements a base framework type.</li>
<li> When you want to use a dictionary to map a build method to a key. This is particularly helpful when fetching factories based on data coming in via a remote procedural call or when fetching factories according to an XML-based configuration file.</li>
</ol>
<p>As stated earlier, .Net does provide a mechanism to do accomplish through reflection.  The problem with using reflection is that it is very slow.  In fact, it is several orders of magnitude slower than the equivalent compiled code.  One might consider creating a generic factory to accomplish the same effect, but there are some surprises that one will encounter along the way.  A naive implementation of a generic factory will, in fact, be just as slow as using reflection.   Luckily, there is a technique for working around the performance issue.</p>
<p><a href="http://mobilecommerceonline.com/blog/?page_id=122">Click here for the rest of the rest of the post, including the code.</a></p>
<img src="http://feeds.feedburner.com/~r/mobilecommerceonline/~4/LD_KBVBcGIw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://mobilecommerceonline.com/blog/?feed=rss2&amp;p=10</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://mobilecommerceonline.com/blog/?p=10</feedburner:origLink></item>
	</channel>
</rss>

