<?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>DeveloperZen &#187; What&#8217;s wrong with this code?</title>
	<atom:link href="http://www.developerzen.com/category/development/whats-wrong-with-this-code/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.developerzen.com</link>
	<description>The essence of software development...</description>
	<lastBuildDate>Wed, 27 Jan 2010 21:24:09 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>What&#8217;s wrong with this code? #2</title>
		<link>http://www.developerzen.com/2007/09/02/whats-wrong-with-this-code-2/</link>
		<comments>http://www.developerzen.com/2007/09/02/whats-wrong-with-this-code-2/#comments</comments>
		<pubDate>Sun, 02 Sep 2007 06:40:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[What's wrong with this code?]]></category>

		<guid isPermaLink="false">http://www.ekampf.com/blog/PermaLink,guid,73da198e-0ccb-4caf-957b-d2558f65f412.aspx</guid>
		<description><![CDATA[Check out the following code snippet:
    static decimal Division(int a, int b) { return a / b; }

Comments (7) imported from www.ekampf.com/blog/:
Sunday, September 02, 2007 9:46:22 AM (GMT Daylight Time, UTC+01:00)
divide with zero..
bb king
Sunday, September 02, 2007 10:54:57 AM (GMT Daylight Time, UTC+01:00)
Absent casting to decimal in return.
HaGever
Sunday, September 02, 2007 2:18:37 [...]]]></description>
			<content:encoded><![CDATA[<p>Check out the following code snippet:
<pre class="code">    <span style="color: #0000ff">static</span> <span style="color: #0000ff">decimal</span> Division(<span style="color: #0000ff">int</span> a, <span style="color: #0000ff">int</span> b) { <span style="color: #0000ff">return</span> a / b; }</pre>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.ekampf.com/blog/2007/09/02/WhatsWrongWithThisCode2.aspx"><img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.ekampf.com/blog/2007/09/02/WhatsWrongWithThisCode2.aspx" border="0"></a></p>
<p>Comments (7) imported from <a href="http://www.ekampf.com/blog/">www.ekampf.com/blog/</a>:</p>
<p>Sunday, September 02, 2007 9:46:22 AM (GMT Daylight Time, UTC+01:00)</p>
<p>divide with zero..</p>
<p>bb king</p>
<p><a name="2eecc5e8-8452-43b4-a210-695dca8d54c2"></a>Sunday, September 02, 2007 10:54:57 AM (GMT Daylight Time, UTC+01:00)</p>
<p>Absent casting to decimal in return.</p>
<p><a href="http://gaaton.blogspot.com/">HaGever</a></p>
<p><a name="689e55d1-ae2f-4848-aa39-8e16347e5555"></a>Sunday, September 02, 2007 2:18:37 PM (GMT Daylight Time, UTC+01:00)</p>
<p>Casting has nothing to do with it. The code compiles and runs without exceptions unless you divide by zero as specified in the first comment.<br />But division by zero is not the only thing wrong here&#8230;</p>
<p><a href="http://www.ekampf.com/blog/">Eran Kampf</a></p>
<p><a name="be906c4b-a3cb-46e6-a193-8ea3de7b131c"></a>Sunday, September 02, 2007 4:28:29 PM (GMT Daylight Time, UTC+01:00)</p>
<p>1 in 5 Americans can divide by 0, such as. Just ask Miss South Carolina.</p>
<p><a href="http://brennan.offwhite.net/blog/">Brennan Stehling</a></p>
<p><a name="a6dce998-dbdf-4d2f-bebb-9e988cabc9c8"></a>Sunday, September 02, 2007 6:06:58 PM (GMT Daylight Time, UTC+01:00)</p>
<p>2Eran Kampf<br />Casting necessary here! <br />Define<br />a = 3<br />b = 2<br />Without casting your result will be 1, but with casting &#8211; 1.5<br />Int/Int return int, but (decimal)int/int = decimal<br />P.S.I don&#8217;t remind a division inasmuch as that this is trivial.<br /> <img src='http://www.developerzen.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  Good luck</p>
<p><a href="http://gaaton.blogspot.com/">HaGever</a></p>
<p><a name="7a61a1cc-cdc3-4fd0-b51a-cec600629e9d"></a>Sunday, September 02, 2007 6:40:16 PM (GMT Daylight Time, UTC+01:00)</p>
<p>Exactly!<br />You found the second point I was aiming at &#8211; dividing integers results an integer. so given a=1 and b=2 the method will return 0 and not 0.5 as expected.<br />On your first comment I understood you want to cast the return value which means doing (decimal)(a/b) which is still wrong.<br />You need to cast a and b before dividing by doing (decimal)a / (decimal)b or by doing what you said in the second comment (decimal)a / b which actually casts a to decimal and then divides it by b.<br />I guess the 2nd snippet was too easy compared to the 1st :\<br />Regards,<br />Eran</p>
<p><a href="http://www.ekampf.com">Eran Kampf</a></p>
<p><a name="bc12b84c-3ec8-4faf-b966-a6860c50db02"></a>Friday, November 23, 2007 9:23:52 AM (GMT Standard Time, UTC+00:00)</p>
<p>This is great! One question: Is there any way around the authentication issue? I have a portal which requires a login/password. Am I out of luck? &#8211;thanks </p>
<p><a href="http://www.euwowgold.com">WOW GOLD</a></p>
<p><strong>Similar Posts:</strong>
<ul class="similar-posts">
<li><a href="http://www.developerzen.com/2008/03/30/developing-a-robust-data-driven-ui-using-wpf-stock-datamodel-sample/" rel="bookmark" title="March 30, 2008">Developing a Robust Data Driven UI Using WPF &#8211; Stock DataModel Sample</a></li>
<li><a href="http://www.developerzen.com/2008/06/26/how-do-you-define-quotgood-codequot/" rel="bookmark" title="June 26, 2008">How Do You Define &#8220;Good Code&#8221;?</a></li>
<li><a href="http://www.developerzen.com/2008/06/10/apology-to-my-readers-buggy-dasblog-contact-form/" rel="bookmark" title="June 10, 2008">Apology to My Readers (Buggy dasBlog Contact Form)</a></li>
<li><a href="http://www.developerzen.com/2009/04/15/developing-a-robust-data-driven-ui-using-wpf-an-overdue-summary-and-full-source-code/" rel="bookmark" title="April 15, 2009">Developing a Robust Data Driven UI Using WPF &ndash; An Overdue Summary (and full source code)</a></li>
<li><a href="http://www.developerzen.com/2008/05/07/im-back/" rel="bookmark" title="May 7, 2008">I&#8217;m Back!</a></li>
</ul>
<p><!-- Similar Posts took 12.081 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.developerzen.com/2007/09/02/whats-wrong-with-this-code-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What&#8217;s wrong with this code? #1 &#8211; Discussion</title>
		<link>http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/</link>
		<comments>http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/#comments</comments>
		<pubDate>Sun, 15 Jul 2007 12:14:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[What's wrong with this code?]]></category>

		<guid isPermaLink="false">http://www.ekampf.com/blog/PermaLink,guid,a609c210-498f-47b8-a0cc-984a43100a45.aspx</guid>
		<description><![CDATA[The Singleton implementation in the snippet I posted works fine as a lazy, thread-safe Singleton as it ensures only one thread can create the instance. However, there&#8217;s a big performance hit caused by the fact that we acquire a lock each time the Singleton&#8217;s instance is requested. Yoav, suggested to fix this performance problem by [...]]]></description>
			<content:encoded><![CDATA[<p>The Singleton implementation in the snippet <a href="http://www.developerzen.com/2007/07/09/whats-wrong-with-this-code-1/">I posted</a> works fine as a lazy, thread-safe Singleton as it ensures only one thread can create the instance. However, there&#8217;s a big performance hit caused by the fact that we acquire a lock each time the Singleton&#8217;s instance is requested. Yoav, suggested to fix this performance problem by checking for <em>null</em> twice &#8211; outside the lock and inside the lock:</p>
<pre class="code"><span style="color: blue;">public static </span><span style="color: #2b91af;">Singleton </span>Instance
{
    <span style="color: blue;">get
    </span>{
        <span style="color: blue;">if </span>(<span style="color: #2b91af;">Singleton</span>._insatnce == <span style="color: blue;">null</span>)
        {
            <span style="color: blue;">lock </span>(_syncRoot)
            {
                <span style="color: blue;">if </span>(<span style="color: #2b91af;">Singleton</span>._insatnce == <span style="color: blue;">null</span>)
                {
                    <span style="color: #2b91af;">Singleton</span>._insatnce = <span style="color: blue;">new </span><span style="color: #2b91af;">Singleton</span>();
                }
            }
        } <span style="color: blue;">return </span><span style="color: #2b91af;">Singleton</span>._insatnce;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a>This code, known as &#8220;Double-Check Locking&#8221; doesn&#8217;t work in the presence of either an optimizing compiler or shared memory multiprocessor. The main reason for this (as explained by <a href="http://blogs.msdn.com/brada/archive/2004/05/12/130935.aspx">Brad</a>) is that the CLR&#8217;s memory model allows non-volatile read\writes to be reordered as long as that change cannot be noticed from the point of view of a single thread. This means that the compiler can reorder write to _<em>instance</em> during initialization and its construction write, causing another thread to see <em>_instance</em> as set even though it wasn&#8217;t initialized yet (appears on stress testing). To prevent such optimizations we can declare _instance to be <em><a href="http://www.google.com/url?sa=t&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fmsdn2.microsoft.com%2Fen-us%2Flibrary%2Fx13ttww7(VS.80).aspx&amp;ei=xg6SRp_7LYiQnQPMtbjVCg&amp;usg=AFQjCNGUPAqpQHtdMpGVrIV81wArNtglZA&amp;sig2=DUOpODoMne9xYBr-4lBWww">volatile</a></em> or by explicitly specifying a memory barrier before accessing the data member using <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemthreadingthreadclassmemorybarriertopic.asp">System.Threading.Thread.MemoryBarrier()</a>. Using <em>Thread</em>.<em>MemoryBarrier()</em> is more efficient than <em>volatile</em> as it allows compiler optimization when barrier is not required:</p>
<pre class="code"><span style="color: blue;">public static </span><span style="color: #2b91af;">Singleton </span>Instance
{
    <span style="color: blue;">get
    </span>{
        <span style="color: blue;">if </span>(<span style="color: #2b91af;">Singleton</span>._insatnce == <span style="color: blue;">null</span>)
        {
            <span style="color: blue;">lock </span>(_syncRoot)
            {
                <span style="color: blue;">if </span>(<span style="color: #2b91af;">Singleton</span>._insatnce == <span style="color: blue;">null</span>)
                {
                    <span style="color: #2b91af;">Singleton </span>newInstance = <span style="color: blue;">new </span><span style="color: #2b91af;">Singleton</span>(); <span style="color: green;">// Ensure all writes used to construct new value have been flushed.  System.Threading.Thread.MemoryBarrier(); Singleton._insatnce = newInstance; // publish the new value
                </span>}
            }
        } <span style="color: blue;">return </span><span style="color: #2b91af;">Singleton</span>._insatnce;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a>Another way of doing the same thing is using <a href="System.Threading.Interlocked.CompareExchange(ref x, y, null);"><em>System.Threading.Interlocked.CompareExchange()</em></a> which also enforces a memory barrier.</p>
<p>Omer, suggested creating the instance of <em>Singleton</em> in the static constructor (which is guaranteed to be thread-safe) rather than in the Instance accessor. While in this implementation you lose some of the flexibility of controlling exactly at which point in time the <em>Singleton</em> instance is created, this kind of control is not really required in most cases and giving up on it allows making the code shorter and less confusing&#8230;</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.ekampf.com/blog/2007/07/15/WhatsWrongWithThisCode1Discussion.aspx"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.ekampf.com/blog/2007/07/15/WhatsWrongWithThisCode1Discussion.aspx" border="0" alt="kick it on DotNetKicks.com" /></a><strong>Similar Posts:</strong>
<ul class="similar-posts">
<li><a href="http://www.developerzen.com/2008/03/24/developing-a-robust-data-driven-ui-using-wpf-the-datamodel/" rel="bookmark" title="March 24, 2008">Developing a Robust Data Driven UI Using WPF &#8211; The DataModel</a></li>
<li><a href="http://www.developerzen.com/2008/03/30/developing-a-robust-data-driven-ui-using-wpf-stock-datamodel-sample/" rel="bookmark" title="March 30, 2008">Developing a Robust Data Driven UI Using WPF &#8211; Stock DataModel Sample</a></li>
<li><a href="http://www.developerzen.com/2009/01/11/aspnet-mvc-rss-feed-action-result/" rel="bookmark" title="January 11, 2009">ASP.NET MVC RSS Feed Action Result</a></li>
<li><a href="http://www.developerzen.com/2009/07/25/moving-your-application-to-amazon-s-cloud/" rel="bookmark" title="July 25, 2009">Moving Your Application to Amazon&rsquo;s Cloud</a></li>
<li><a href="http://www.developerzen.com/2009/04/15/developing-a-robust-data-driven-ui-using-wpf-an-overdue-summary-and-full-source-code/" rel="bookmark" title="April 15, 2009">Developing a Robust Data Driven UI Using WPF &ndash; An Overdue Summary (and full source code)</a></li>
</ul>
<p><!-- Similar Posts took 16.126 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>What&#8217;s wrong with this code? #1</title>
		<link>http://www.developerzen.com/2007/07/09/whats-wrong-with-this-code-1/</link>
		<comments>http://www.developerzen.com/2007/07/09/whats-wrong-with-this-code-1/#comments</comments>
		<pubDate>Mon, 09 Jul 2007 06:19:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[What's wrong with this code?]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://www.ekampf.com/blog/PermaLink,guid,a891f90e-325e-4316-ade9-d26a5f92e62a.aspx</guid>
		<description><![CDATA[I decided to start a new column gathering all sorts of &#8220;what&#8217;s wrong with this code?&#8221; snippets. Why?

Its fun.
Its good for interview questions.
It starts discussions. More interesting than just talking (or writing) to myself.

So, here&#8217;s what I plan:

I post a code snippet (most probably C# but I&#8217;m not setting constraints on myself)
You comment on what&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>I decided to start a new column gathering all sorts of &#8220;what&#8217;s wrong with this code?&#8221; snippets. Why?</p>
<ol>
<li>Its fun.</li>
<li>Its good for interview questions.</li>
<li>It starts discussions. More interesting than just talking (or writing) to myself.</li>
</ol>
<p>So, here&#8217;s what I plan:</p>
<ol>
<li>I post a code snippet (most probably C# but I&#8217;m not setting constraints on myself)</li>
<li>You comment on what&#8217;s wrong with the code on the snippet</li>
<li>I post my answer, interesting comments, etc. (you can comment on my answer too <img src="smilies/happy.gif" alt=":-)" />)</li>
</ol>
<p>* Note that these posts are syndicated on <a href="http://blogs.microsoft.co.il">blogs.microsoft.co.il</a> (and maybe some other places) so please leave your comments at the main blog &#8211; <a href="http://www.ekampf.com/blog/">www.ekampf.com/blog/</a> ** I know there are many &#8220;What&#8217;s wrong with this code?&#8221; out there already. I&#8217;ll try not to recycle (too much <img src='http://www.developerzen.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ) When looking at these snippets note the following &#8220;Bad Code&#8221; classifications: Confusing code, Overly complex code, Performance Issues, Buggy. So, to start with an easy one (I think), check out the following Singleton implementation:</p>
<pre class="code"><span style="color: blue;">public sealed class </span><span style="color: #2b91af;">Singleton
</span>{
    <span style="color: blue;">private </span>Singleton() { } 

    <span style="color: blue;">private static </span><span style="color: #2b91af;">Singleton </span>_insatnce;
    <span style="color: blue;">private static object </span>_syncRoot = <span style="color: blue;">new </span><span style="color: #2b91af;">Object</span>();

    <span style="color: blue;">public static </span><span style="color: #2b91af;">Singleton </span>Instance
    {
        <span style="color: blue;">get
        </span>{
            <span style="color: blue;">lock </span>(_syncRoot)
            {
                <span style="color: blue;">if </span>(<span style="color: #2b91af;">Singleton</span>._insatnce == <span style="color: blue;">null</span>)
                {
                    <span style="color: #2b91af;">Singleton</span>._insatnce = <span style="color: blue;">new </span><span style="color: #2b91af;">Singleton</span>();
                }
                <span style="color: blue;">return </span><span style="color: #2b91af;">Singleton</span>._insatnce;
            }
        }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><span style="color: #ff0000;">Update July 16th, 2007:</span> I&#8217;ve posted the answer and a summary on the comments at <a title="What's wrong with this code? #1 - Discussion" href="http://www.ekampf.com/blog/2007/07/15/WhatsWrongWithThisCode1Discussion.aspx">the following post</a>.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://www.ekampf.com/blog/2007/07/09/WhatsWrongWithThisCode1.aspx"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.ekampf.com/blog/2007/07/09/WhatsWrongWithThisCode1.aspx" border="0" alt="kick it on DotNetKicks.com" /></a><strong>Similar Posts:</strong>
<ul class="similar-posts">
<li><a href="http://www.developerzen.com/2009/04/15/developing-a-robust-data-driven-ui-using-wpf-an-overdue-summary-and-full-source-code/" rel="bookmark" title="April 15, 2009">Developing a Robust Data Driven UI Using WPF &ndash; An Overdue Summary (and full source code)</a></li>
<li><a href="http://www.developerzen.com/2008/06/10/apology-to-my-readers-buggy-dasblog-contact-form/" rel="bookmark" title="June 10, 2008">Apology to My Readers (Buggy dasBlog Contact Form)</a></li>
<li><a href="http://www.developerzen.com/2008/03/30/developing-a-robust-data-driven-ui-using-wpf-stock-datamodel-sample/" rel="bookmark" title="March 30, 2008">Developing a Robust Data Driven UI Using WPF &#8211; Stock DataModel Sample</a></li>
<li><a href="http://www.developerzen.com/2008/08/05/migrating-from-dasblog-to-wordpress/" rel="bookmark" title="August 5, 2008">Migrating from dasBlog to Wordpress</a></li>
<li><a href="http://www.developerzen.com/2008/06/22/the-complete-checklist-for-cleaning-up-your-machine/" rel="bookmark" title="June 22, 2008">The Complete Checklist for Cleaning Up Your Machine</a></li>
</ul>
<p><!-- Similar Posts took 14.733 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.developerzen.com/2007/07/09/whats-wrong-with-this-code-1/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
