<?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>FormatException &#187; coding standards</title>
	<atom:link href="http://www.formatexception.com/tag/coding-standards/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.formatexception.com</link>
	<description>Ramblings on developing in the Windows World</description>
	<lastBuildDate>Fri, 23 Sep 2011 15:34:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>First in a series of many</title>
		<link>http://www.formatexception.com/2008/09/first-in-a-series-of-many/</link>
		<comments>http://www.formatexception.com/2008/09/first-in-a-series-of-many/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 14:51:12 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[coding standards]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=69</guid>
		<description><![CDATA[I &#8216;ve been trying to come up with things that lead to a series of follows up stuff.  This way I don&#8217;t have to think too hard about coming up with subjects and it makes writing them easier since I don&#8217;t have to spend so much time in general on them.  And now from: http://www.ayende.com/Blog/archive/2008/08/27/What-I-am-working-on.aspx [...]]]></description>
			<content:encoded><![CDATA[<p><!--StartFragment -->I &#8216;ve been trying to come up with things that lead to a series of follows up stuff.  This way I don&#8217;t have to think too hard about coming up with subjects <img src='http://www.formatexception.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  and it makes writing them easier since I don&#8217;t have to spend so much time in general on them.  And now from:</p>
<p><a class="moz-txt-link-freetext" href="http://www.ayende.com/Blog/archive/2008/08/27/What-I-am-working-on.aspx">http://www.ayende.com/Blog/archive/2008/08/27/What-I-am-working-on.aspx</a></p>
<p>Oren is his name and he is one of the bloggers I follow pretty close.  He&#8217;s been doing some pretty incredible stuff with a product he helped write called &#8220;Rhino Mocks&#8221; that allows you to create mock objects for testing and to set test conditions on those objects (ok, there&#8217;s a lot more but that scratches the surface) and in general he&#8217;s a pretty incredible coder.</p>
<p>Well, recently he posted some code that seems essentially how not to develop software with so many bad coding standards it would keep me busy for awhile.  Take a look at the below code:</p>
<div style="background-color: #FFF;overflow : auto;">
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> TaxCalculator
{
    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">string</span> conStr;
    <span style="color: #0000ff;">private</span> DataSet rates;

    <span style="color: #0000ff;">public</span> TaxCalculator(<span style="color: #0000ff;">string</span> conStr)
    {
        <span style="color: #0000ff;">this</span>.conStr = conStr;
        <span style="color: #0000ff;">using</span> (SqlConnection con = <span style="color: #0000ff;">new</span> SqlConnection(conStr))
        {
            con.Open();
            <span style="color: #0000ff;">using</span> (SqlCommand cmd = <span style="color: #0000ff;">new</span> SqlCommand("<span style="color: #8b0000;">SELECT * FROM tblTxRtes</span>", con))
            {
                rates = <span style="color: #0000ff;">new</span> DataSet();
                <span style="color: #0000ff;">new</span> SqlDataAdapter(cmd).Fill(rates);
                Log.Write("<span style="color: #8b0000;">Read </span>" + rates.Tables[0].Rows.Count + <br/>"<span style="color: #8b0000;"> rates from database</span>");
                <span style="color: #0000ff;">if</span> (rates.Tables[0].Rows.Count == 0)
                {
                    MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage("<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:important@legacy.org">important@legacy.org</a></span>", "<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:joe@legacy.com">joe@legacy.com</a></span>");
                    msg.Subject = "<span style="color: #8b0000;">NO RATES IN DATABASE!!!!!</span>";
                    msg.Priority = MailPriority.High;
                    <span style="color: #0000ff;">new</span> SmtpClient("<span style="color: #8b0000;">mail.legacy.com</span>", 9089).Send(msg);
                    Log.Write("<span style="color: #8b0000;">No rates for taxes found in </span>" + conStr);
                    <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> ApplicationException("<span style="color: #8b0000;">No rates, Joe forgot to load the rates AGAIN!</span>");
                }
            }
        }
    }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">bool</span> Process(XmlDocument transaction)
    {
        <span style="color: #0000ff;">try</span>
        {
            Hashtable tx2tot = <span style="color: #0000ff;">new</span> Hashtable();
            <span style="color: #0000ff;">foreach</span> (XmlNode o <span style="color: #0000ff;">in</span> transaction.FirstChild.ChildNodes)
            {
            restart:
                <span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == "<span style="color: #8b0000;">2</span>")
                {
                    Log.Write("<span style="color: #8b0000;">Type two transaction processing</span>");
                    <span style="color: #0000ff;">decimal</span> total = <span style="color: #0000ff;">decimal</span>.Parse(o.Attributes["<span style="color: #8b0000;">tot</span>"].Value);
                    XmlAttribute attribute = transaction.CreateAttribute("<span style="color: #8b0000;">tax</span>");
                    <span style="color: #0000ff;">decimal</span> r = -1;
                    <span style="color: #0000ff;">foreach</span> (DataRow dataRow <span style="color: #0000ff;">in</span> rates.Tables[0].Rows)
                    {
                        <span style="color: #0000ff;">if</span> ((<span style="color: #0000ff;">string</span>)dataRow[2] == o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value)
                        {
                            r = <span style="color: #0000ff;">decimal</span>.Parse(dataRow[2].ToString());
                        }
                    }
                    Log.Write("<span style="color: #8b0000;">Rate calculated and is: </span>" + r);
                    o.Attributes.Append(attribute);
                    <span style="color: #0000ff;">if</span> (r == -1)
                    {
                        MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage("<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:important@legacy.org">important@legacy.org</a></span>", "<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:joe@legacy.com">joe@legacy.com</a></span>");
                        msg.Subject = "<span style="color: #8b0000;">NO RATES FOR </span>" + o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value + "<span style="color: #8b0000;"> TRANSACTION !!!!ABORTED!!!!</span>";
                        msg.Priority = MailPriority.High;
                        <span style="color: #0000ff;">new</span> SmtpClient("<span style="color: #8b0000;">mail.legacy.com</span>", 9089).Send(msg);
                        Log.Write("<span style="color: #8b0000;">No rate for transaction in tranasction state</span>");
                        <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> ApplicationException("<span style="color: #8b0000;">No rates, Joe forgot to load the rates AGAIN!</span>");
                    }
                    tx2tot.Add(o.Attributes["<span style="color: #8b0000;">id</span>"], total * r);
                    attribute.Value = (total * r).ToString();
                }
                <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == "<span style="color: #8b0000;">1</span>")
                {
                    <span style="color: #008000;">//2006-05-02 just need to do the calc</span>
                    <span style="color: #0000ff;">decimal</span> total = 0;
                    <span style="color: #0000ff;">foreach</span> (XmlNode i <span style="color: #0000ff;">in</span> o.ChildNodes)
                    {
                        total += ProductPriceByNode(i);
                    }
                    <span style="color: #0000ff;">try</span>
                    {
                        <span style="color: #008000;">// 2007-02-19 not so simple, TX has different rule</span>
                        <span style="color: #0000ff;">if</span> (o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value == "<span style="color: #8b0000;">TX</span>")
                        {
                            total *= (<span style="color: #0000ff;">decimal</span>)1.02;
                        }
                    }
                    <span style="color: #0000ff;">catch</span> (NullReferenceException)
                    {
                        XmlElement element = transaction.CreateElement("<span style="color: #8b0000;">state</span>");
                        element.Value = "<span style="color: #8b0000;">NJ</span>";
                        o.SelectSingleNode("<span style="color: #8b0000;">//cust-details</span>").AppendChild(element);
                    }
                    XmlAttribute attribute = transaction.CreateAttribute("<span style="color: #8b0000;">tax</span>");
                    <span style="color: #0000ff;">decimal</span> r = -1;
                    <span style="color: #0000ff;">foreach</span> (DataRow dataRow <span style="color: #0000ff;">in</span> rates.Tables[0].Rows)
                    {
                        <span style="color: #0000ff;">if</span> ((<span style="color: #0000ff;">string</span>)dataRow[2] == o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value)
                        {
                            r = <span style="color: #0000ff;">decimal</span>.Parse(dataRow[2].ToString());
                        }
                    }
                    <span style="color: #0000ff;">if</span> (r == -1)
                    {
                        MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage("<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:important@legacy.org">important@legacy.org</a></span>", "<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:joe@legacy.com">joe@legacy.com</a></span>");
                        msg.Subject = "<span style="color: #8b0000;">NO RATES FOR </span>" + o.SelectSingleNode("<span style="color: #8b0000;">//cust-details/state</span>").Value + "<span style="color: #8b0000;"> TRANSACTION !!!!ABORTED!!!!</span>";
                        msg.Priority = MailPriority.High;
                        <span style="color: #0000ff;">new</span> SmtpClient("<span style="color: #8b0000;">mail.legacy.com</span>", 9089).Send(msg);
                        <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> ApplicationException("<span style="color: #8b0000;">No rates, Joe forgot to load the rates AGAIN!</span>");
                    }
                    attribute.Value = (total * r).ToString();
                    tx2tot.Add(o.Attributes["<span style="color: #8b0000;">id</span>"], total * r);
                    o.Attributes.Append(attribute);
                }
                <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == "<span style="color: #8b0000;">@</span>")
                {
                    o.Attributes["<span style="color: #8b0000;">type</span>"].Value = "<span style="color: #8b0000;">2</span>";
                    <span style="color: #0000ff;">goto</span> restart;
                    <span style="color: #008000;">// 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to</span>
                    <span style="color: #008000;">// fix this because they won't until sep-07</span>
                }
                <span style="color: #0000ff;">else</span>
                {
                    <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> Exception("<span style="color: #8b0000;">UNKNOWN TX TYPE</span>");
                }
            }
            SqlConnection con2 = <span style="color: #0000ff;">new</span> SqlConnection(conStr);
            SqlCommand cmd2 = <span style="color: #0000ff;">new</span> SqlCommand();
            cmd2.Connection = con2;
            con2.Open();
            <span style="color: #0000ff;">foreach</span> (DictionaryEntry d <span style="color: #0000ff;">in</span> tx2tot)
            {
                cmd2.CommandText = "<span style="color: #8b0000;">usp_TrackTxNew</span>";
                cmd2.Parameters.Add("<span style="color: #8b0000;">cid</span>", transaction.SelectSingleNode("<span style="color: #8b0000;">//cust-details/@id</span>").Value);
                cmd2.Parameters.Add("<span style="color: #8b0000;">tx</span>", d.Key);
                cmd2.Parameters.Add("<span style="color: #8b0000;">tot</span>", d.Value);
                cmd2.ExecuteNonQuery();
            }
            con2.Close();
        }
        <span style="color: #0000ff;">catch</span> (Exception e)
        {
            <span style="color: #0000ff;">if</span> (e.Message == "<span style="color: #8b0000;">UNKNOWN TX TYPE</span>")
            {
                <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span>;
            }
            <span style="color: #0000ff;">throw</span> e;
        }
        <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span>;
    }

    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">decimal</span> ProductPriceByNode(XmlNode item)
    {
        <span style="color: #0000ff;">using</span> (SqlConnection con = <span style="color: #0000ff;">new</span> SqlConnection(conStr))
        {
            con.Open();
            <span style="color: #0000ff;">using</span> (SqlCommand cmd = <span style="color: #0000ff;">new</span> SqlCommand("<span style="color: #8b0000;">SELECT * FROM tblProducts WHERE pid=</span>" + item.Attributes["<span style="color: #8b0000;">id</span>"], con))
            {
                DataSet <span style="color: #0000ff;">set</span> = <span style="color: #0000ff;">new</span> DataSet();
                <span style="color: #0000ff;">new</span> SqlDataAdapter(cmd).Fill(<span style="color: #0000ff;">set</span>);
                <span style="color: #0000ff;">return</span> (<span style="color: #0000ff;">decimal</span>)<span style="color: #0000ff;">set</span>.Tables[0].Rows[0][4];

            }
        }
    }
}</pre>
</div>
<p>If this code doesn&#8217;t make you shudder I worry about you and suspect you shouldn&#8217;t be working as a computer programmer.<br />
Over the course of the next few weeks, along with my posts on LINQ I want to spend some time analyzing what is wrong with this and help to try to define some of the established coding standards with .Net as well as coding in general.</p>
<p>Let&#8217;s start with the obvious.  We all know I am anti-goto, with good reason.  There is really no place in any modern high-level language for gotos.  Look at this:</p>
<p><span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == &#8220;<span style="color: #8b0000;">@</span>&#8220;)<br />
{<br />
        o.Attributes["<span style="color: #8b0000;">type</span>"].Value = &#8220;<span style="color: #8b0000;">2</span>&#8220;; <span style="color: #0000ff;"><br />
        goto</span> restart;<br />
        <span style="color: #008000;">// 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to</span> <span style="color: #008000;"><br />
        // fix this because they won&#8217;t until sep-07</span><br />
}</p>
<p>Okay, if you look at the flow of the foreach this is in this else/if and breaks the flow of the code sending the execution back up to the top in mid-loop restarting everything over again. </p>
<p>But Brian, this had to be done, don&#8217;t you see the comments?</p>
<p>No my young padawan, it doesn&#8217;t.  I&#8217;m not saying the fix for this shouldn&#8217;t be in place, what I&#8217;m saying is that the goto shouldn&#8217;t be there.  If the original programmer thought about this a bit more he would have seen that if he simply put the statement at the beginning of the foreach as an if statement like:</p>
<p><span style="color: #0000ff;">if</span> (o.Attributes["<span style="color: #8b0000;">type</span>"].Value == &#8220;<span style="color: #8b0000;">@</span>&#8220;)<br />
{<br />
        o.Attributes["<span style="color: #8b0000;">type</span>"].Value = &#8220;<span style="color: #8b0000;">2</span>&#8220;; <span style="color: #0000ff;"><br />
</span>        <span style="color: #008000;">// 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to</span> <span style="color: #008000;"><br />
        // fix this because they won&#8217;t until sep-07</span><br />
}</p>
<p> it would have had the same effect without needing the goto.</p>
<p>But Brian, by putting it later in the code then most of the time you will be able to try and capture the ifs earlier and then you won&#8217;t have to do a compare on every row for &#8220;@&#8221;. </p>
<p>So what?  How do you know that every row won&#8217;t have the &#8220;@&#8221; for the value?  In that case you actually hurt your code execution by not putting the if at the beginning of the foreach loop.  Plain and simple gotos hurt code (see my earlier post on gotos with references on such).  The studies have been done and there are no reason for them in a modern language.</p>
<p>On to the next point of the code:</p>
<pre>MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage("<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:important@legacy.org">important@legacy.org</a></span>", "<span style="color: #8b0000;"><a class="moz-txt-link-abbreviated" href="mailto:joe@legacy.com">joe@legacy.com</a></span>");</pre>
<p>Well, what&#8217;s wrong with this? </p>
<p>What if Joe quits the company?  What if Important quits the company?  These values should not be embedded in the code. </p>
<p>But Brian, Important is a not person you silly guy! It&#8217;s a mailing group.</p>
<p>Wow, sarcasm is not lost on you.</p>
<p>In modern .Net applications you have the Settings.  This allows you to store values in an easy to use xml file.  To get the values back out you don&#8217;t have to even do any special parsing, you just do (assuming you named your settings &#8220;MySettings&#8221;):</p>
<pre>MailMessage msg = <span style="color: #0000ff;">new</span> MailMessage(MySettings.WhoToSendEmailTo);</pre>
<p>That&#8217;s right.  When you add settings to your application you can then simply refer to the values in them directly as a property of the static Settings object in your project.  Then, in the future if Joe or Important should no longer get the emails then you simply modify the xml file in the application directory (or use the Visual Studio settings editor) and change who it should go to.  No need to recompile.  It&#8217;s that simple.  To add a settings, right click on the project name, select &#8220;Add New&#8221; and click on Settings file.  Name it as you like and Visual Studio will open a settings editor where you can add these properties and values.</p>
<p>Brian, you&#8217;re a dumb ass.  I tried this.  My application spans multiple projects and the settings file is only scoped at the project level.</p>
<p>Fine, if you want to be that way be that way.  Don&#8217;t use the settings features built in to the framework.  But whatever you do don&#8217;t embed this stuff into the application code.  If your smart and have been using a data access layer (DAL) like nhibernate or netTiers then getting and storing these values in the database should be trivial.  While up front it&#8217;s a bit more of a pain, on the back end it is easier because then for each instance of your application running you don&#8217;t have to modify the settings file and deploy to each application.  You just get the values out of the database.</p>
<p>Well, that&#8217;s it for now.  Hopefully you all might be interested in this and if you aren&#8217;t you&#8217;ll still be getting the code.  Doing a series like this is easy for me and allows me more time to do real work so there <img src='http://www.formatexception.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Next time we&#8217;ll look at DALs and refactoring.</p>
<p>Later &#8216;yall,<br />
Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ffirst-in-a-series-of-many%2F&amp;t=First%20in%20a%20series%20of%20many" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ffirst-in-a-series-of-many%2F&amp;t=First%20in%20a%20series%20of%20many" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/first-in-a-series-of-many/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

