<?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>BinzBlog - Robert Binzley : robert@binzley.net</title>
	<atom:link href="http://www.binzley.net/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.binzley.net</link>
	<description>Musings on pragmatic .net solution development.</description>
	<lastBuildDate>Mon, 02 Aug 2010 15:33:18 +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>Why ORM Should Be Used, At Least Most Of TheTime</title>
		<link>http://www.binzley.net/?p=464</link>
		<comments>http://www.binzley.net/?p=464#comments</comments>
		<pubDate>Sat, 31 Jul 2010 20:20:22 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[EF4]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=464</guid>
		<description><![CDATA[Every so often a new project starts up near me, and this project requires interacting with a database.   Someone who has used an ORM (Object Relation Mapping) tool in the past suggests using it again.   Whether it is nHibernate, LLBLGen Pro or Entity Framework, the person must have had a somewhat positive experience, [...]]]></description>
			<content:encoded><![CDATA[<p>Every so often a new project starts up near me, and this project requires interacting with a database.   Someone who has used an <a href="http://en.wikipedia.org/wiki/Object-relational_mapping">ORM (Object Relation Mapping) </a>tool in the past suggests using it again.   Whether it is <a href="http://en.wikipedia.org/wiki/NHibernate">nHibernate</a>, <a href="http://www.llblgen.com/defaultgeneric.aspx">LLBLGen Pro</a> or <a href="http://msdn.microsoft.com/en-us/data/aa937723.aspx">Entity Framework</a>, the person must have had a somewhat positive experience, or they wouldn&#8217;t suggest using again.   </p>
<p>Almost as certainly someone who has traditionally put <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> and some business logic in stored procedures and not used an ORM tool in the past fights the suggestion to use the ORM tool.  They most likely have gotten good at writing and tweaking stored procedures and had a positive experience with this approach or they would not fight against the ORM tool.  As usual there is no right or wrong way, just different approaches that may be more appropriate for the task at hand.</p>
<p><strong>Why Use An ORM Tool:</strong></p>
<p>The reason I suggest that ORM tools are the right choice most of the time is because most projects I see have aggressive time lines and limited development resources.  To that end the ORM tool lets me write a lot less code to do the same amount of work.  Take the below two methods, one gets all customers using Entity Framework 4 and the other gets the list manually using a SqlConnection, SqlCommand and SqlDataReader:</p>
<pre class="brush: csharp;">
/// &lt;summary&gt;
        /// Method using ORM To Get Customers
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public List&lt;Customer&gt; GetAllCustomersEF()
        {
            using (NorthwindEntities nwDB = new NorthwindEntities())
            {
                return (from cus in nwDB.Customers
                        select cus).ToList();

            }
        }

        /// &lt;summary&gt;
        /// Method using straight SQL to get all customers
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public List&lt;Customer&gt; GetAllCustomersSQL()
        {
            var retList = new List&lt;Customer&gt;();

            string cmdText = &quot;SELECT * FROM CUSTOMERS&quot;;

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString))
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                conn.Open();
                using (SqlDataReader dataRD = cmd.ExecuteReader())
                {
                    while(dataRD.Read())
                    {
                        retList.Add(CreateCustomerFromDataReader(dataRD));
                    }
                }

            }

            return retList;

        }

        /// &lt;summary&gt;
        /// Method To Create Customer From Datareader record
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;dataRD&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        private static Customer CreateCustomerFromDataReader(SqlDataReader dataRD)
        {
            Customer customer = new Customer();
            customer.Address = dataRD[&quot;Address&quot;].ToString();
            customer.City = dataRD[&quot;City&quot;].ToString();
            customer.CustomerID = dataRD[&quot;CustomerID&quot;].ToString();
            customer.CompanyName = dataRD[&quot;CompanyName&quot;].ToString();
            customer.ContactName = dataRD[&quot;ContactName&quot;].ToString();
            //.. repeat until all fields full

            return customer;
        }
</pre>
<p>As you can see above there is a lot less code required using Entity Framework 4.  The data class, Customer, is actually code genned for me.  And the projection into the object from the database is also done for me.  All I have to do is write a query using <a href="http://en.wikipedia.org/wiki/LINQ">LINQ</a> syntax.</p>
<p>To get the data using a SQLCommand I have write the query in SQL either inline (as is done above) or in a stored procedure.  I have to then iterate through the results and fill a Customer class of my own making, so I have to create and maintain the code for projecting the data from the database into my objects.</p>
<p>The above is a very simple case,  add filtering or prefetching data in the object graph and the amount of extra code I have to write in the straight sql solution grows exponentially compared to the Entity 4 solution.  Below is possible code for grabbing all customers but with their orders also.</p>
<pre class="brush: csharp;">
/// &lt;summary&gt;
        /// Method using ORM To Get Customers
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public List&lt;Customer&gt; GetAllCustomersWithOrdersEF()
        {
            using (NorthwindEntities nwDB = new NorthwindEntities())
            {
                return (from cus in nwDB.Customers.Include(&quot;Orders&quot;)
                        select cus).ToList();

            }
        }

        /// &lt;summary&gt;
        /// Method using straight SQL to get all customers
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public List&lt;Customer&gt; GetAllCustomersWithOrdersAllDataSQL()
        {
            var retList = new List&lt;Customer&gt;();

            string cmdText = &quot;SELECT * FROM CUSTOMERS&quot;
                             + &quot; LEFT JOIN ORDERS &quot;
                             + &quot; ON CUSTOMERS.CustomerID = ORDERS.CustomerID Order By Customers.CustomerID&quot;;

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString))
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                conn.Open();
                using (SqlDataReader dataRD = cmd.ExecuteReader())
                {
                    Customer customer = null;
                    string customerID = &quot;&quot;;
                    while(dataRD.Read())
                    {
                        if (customerID != dataRD[&quot;CustomerID&quot;].ToString())
                        {
                            if (customer != null)
                            {
                                retList.Add(customer);
                            }
                            customer = CreateCustomerFromDataReader(dataRD);
                        }

                        customer.Orders.Add(CreateOrderFromDataReader(dataRD));
                    }
                    if (customer != null)
                    {
                        retList.Add(customer);
                    }
                }

            }

            return retList;

        }

        private Order CreateOrderFromDataReader(SqlDataReader dataRD)
        {
            Order retOrder = new Order();
            ///...fill order
            ///
            return retOrder;
        }

        /// &lt;summary&gt;
        /// Method To Create Customer From Datareader record
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;dataRD&quot;&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        private static Customer CreateCustomerFromDataReader(SqlDataReader dataRD)
        {
            Customer customer = new Customer();
            customer.Address = dataRD[&quot;Address&quot;].ToString();
            customer.City = dataRD[&quot;City&quot;].ToString();
            customer.CustomerID = dataRD[&quot;CustomerID&quot;].ToString();
            customer.CompanyName = dataRD[&quot;CompanyName&quot;].ToString();
            customer.ContactName = dataRD[&quot;ContactName&quot;].ToString();
            //.. repeat until all fields full

            return customer;
        }
</pre>
<p>To add the prefetch of Orders in the straight SQL solution I have to write code to project into my customer than check each row to see if the customer changes, and then add orders to the customer.  This supposes I do not mind that the customer data is duplicated for each order returned for the same company.  If I want to optimize data transfer things get even more complex.</p>
<p>Even in a fairly simple example I have a lot less code to write and maintain using the ORM solution.  When the database schema changes this means I have less code I&#8217;ll have to update to accommodate a schema change.  If the ORM is statically typed, as is Entity Framework 4 and LLBL Gen Pro, then I&#8217;ll also have the benefit of seeing where my code breaks when the schema is changed at compile time.   The  less code I have to write by hand and alter when I make changes to my  data model the better, and the easier these changes are to find the better.</p>
<p>ORM tools have not always been so friendly to data model changes.  nHibernate uses an XML mapping file, or used to.  Up until Entity Framework4 synchronizing changes to your schema into code was not that straightforward.    LLBL Gen Pro code generates its data layer so handles changes to the schema pretty well, but was hard to learn to use.  Even given these earlier drawbacks, I would still argue they allow more rapid development with limited resources available.</p>
<p>Also, ORM tools allow you to rely on the expertise of those who wrote them when it comes to creating the SQL that is actually run on the database.  If you have a DBA and are confident that you can tweak your own SQL effectively this isn&#8217;t an issue.  More and more, however, I run into projects where no one has a very deep SQL background.</p>
<p><strong>Why Use Straight SQL:</strong></p>
<p>None of this is to say that straight SQL does not have its place.  I always use stored procedures in reporting oriented applications, as their needs are heavily data processing intensive.   In circumstances where performance is the highest priority and time line and available resources are not an issue then the straight SQL solution is better suited.  If you know what you are doing you can achieve higher performance with your own code.  However, you have to know what you are doing.  Writing your own data layer does not guarantee better performance.</p>
<p><strong>Conclusion:</strong></p>
<p>As the title suggests I believe an ORM tool is the best choice most of the time.  Most projects have short time frames and limited resources.  Where performance is the absolute top priority or you have heavily data processing tasks in the application then a straight SQL approach may make sense.  Even in these cases I might suggest a hybrid approach, where straight SQL is used only where required, so areas of the application that don&#8217;t require heavy data processing or top performance are easier to build and maintain.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=464</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Restful Services, Who Needs A WSDL Anyway?</title>
		<link>http://www.binzley.net/?p=460</link>
		<comments>http://www.binzley.net/?p=460#comments</comments>
		<pubDate>Sun, 25 Jul 2010 18:28:17 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Rest]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=460</guid>
		<description><![CDATA[I remember back when I first started working with web services how happy I was that .net created it&#8217;s own client proxies.  Hitting any web service that exposed a WSDL was a snap in .net, I didn&#8217;t need to know anything about SOAP or even XML for that matter.  All I need was [...]]]></description>
			<content:encoded><![CDATA[<p>I remember back when I first started working with <a href="http://en.wikipedia.org/wiki/Web_services">web services</a> how happy I was that .net created it&#8217;s own client proxies.  Hitting any web service that exposed a <a href="http://en.wikipedia.org/wiki/Wsdl">WSDL</a> was a snap in .net, I didn&#8217;t need to know anything about <a href="http://en.wikipedia.org/wiki/SOAP_%28protocol%29">SOAP</a> or even XML for that matter.  All I need was to created my trusted web reference and off I went consuming web services both near and far.</p>
<p>Now later I came to realize that, in .net 2.0 anyway, all the services and their arguments were created in proxies with their own name spaces, and the proxy arguments had only public fields, not properties so couldn&#8217;t bind to them.  This prompted me to create wrappers around all .net 2.0 services to transform arguments and returns types to common objects and such. <a href="http://msdn.microsoft.com/en-us/netframework/aa663324.aspx">Windows Communication Foundation (WCF)</a> came along and took care of all these issues for me.  Still, even with the introduction of WCF I was pointing my trusted IDE at a WSDL for the most part, and it was doing it&#8217;s client proxy magic.  I still needed no jedi like WSDL knowledge, although to configure WCF I know actually did need to know something about XML (especially setting up certificates and error handling).</p>
<p>Now we come the world of <a href="http://en.wikipedia.org/wiki/REST">Restful services</a>.  No more WSDL, but also, no more proxy magic!  I can&#8217;t point my trusted IDE at a URL and have things done for me.  Now I have to actually do things for myself, sort of.  It seems most publishers of Restful services (Amazon, Netflix) give you documentation about their API, so you can consume their services directly yourself, but they also provide client implementations in popular platforms, so you don&#8217;t have to write code against the restful API yourself if you don&#8217;t want to.  It&#8217;s probably better since I think I have more faith in client proxy code created by the publisher of the Restful API then I do with the code generated by my trusty IDE.  Plus I can look at and makes sense of the communication in an interaction with a Restful API.  SOAP was always a mystery, especially when it came to authentication.</p>
<p>Now as we start publishing Restful services ourselves on my current project, I&#8217;m eager to publish client proxies for those that will consume them. I Feel like I&#8217;m returning the favor of the Restful services we&#8217;re consuming by using client proxies provided by the service itself.  We are using WCF to host or Restful services and that in itself has some interesting nuances.  Microsoft publishes a <a href="http://www.asp.net/downloads/starter-kits/wcf-rest">Restful WCF starter kit</a>, which is useful to get up something that requires very little configuration.  We quickly ran into problems when needing to configure our service to use HTTPS and authentication and ended up abandoning the starter kits base service object <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webservicehost.aspx">WebServiceHost</a>, for the traditional WCF <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx">ServiceHost</a> configured with a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.webhttpbinding.aspx">WebHTTPBinding</a> and <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.webhttpbehavior.aspx">WebHTTPBehavior</a>.  Using these allowed us to configure our Restful Services with the same <a href="http://msdn.microsoft.com/en-us/library/ms731734.aspx">XML constructs</a> we used in our SOAP based WCF services.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=460</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>All IQueryables Are Not The Same</title>
		<link>http://www.binzley.net/?p=432</link>
		<comments>http://www.binzley.net/?p=432#comments</comments>
		<pubDate>Sun, 30 May 2010 14:31:09 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[llbl]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=432</guid>
		<description><![CDATA[On my current project we use an Object Relational Mapping (ORM) tool named LLBL Gen Pro.  LLBL has a really nice LINQ implementation over it which allows for writing queries much more naturally and in a strongly typed environment.  nHibernate has long had a query language that looked similar to SQL named HQL (Hibernate Query [...]]]></description>
			<content:encoded><![CDATA[<p>On my current project we use an Object Relational Mapping (ORM) tool named <a href="http://www.llblgen.com/defaultgeneric.aspx">LLBL Gen Pro</a>.  LLBL has a really nice <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx">LINQ</a> implementation over it which allows for writing queries much more naturally and in a strongly typed environment.  <a href="http://nhforge.org/Default.aspx">nHibernate</a> has long had a query language that looked similar to SQL named <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html">HQL</a> (Hibernate Query Language).  Unlike LINQ, HQL was weakly typed so changes to types wouldn&#8217;t result in compile time errors.  Since LINQ is strongly typed this is not an issue.  When we decided on LLBL Gen Pro it was before <a href="http://ayende.com/Blog/archive/2009/07/26/nhibernate-linq-1.0-released.aspx">nHibernate Linq</a> existed.  We liked being able to use LINQ for querying since could leverage the learning from using LINQ to Objects from a syntactic perspective.</p>
<p>The above is why we choose LLBL and we have been please with the LINQ implementation.  When using LINQ, however, it is important to keep in mind who is the daddy of an IQueryable or IEnumerable you are working with.  </p>
<p>I recently came across a scenario like the below where I retrieved a result set  and then further refine the result set.</p>
<pre class="brush: csharp;">

//--query against IQueryable that is LLBL Entity
var codes = from c in companyQ
                 where c.CompanyID == companyID
                 select c.PromoCodes;

if (codes.Count() &gt; 0)
            {
               //--get the freetrial from result set
                var freeTrial = codes.Where(c =&gt; c.CodeType == (int)CodeTypeEnum.FreeTrial).SingleOrDefault();

              //--get list prepaid from result set
                var prePaids = codes.Where(c =&gt; c.CodeType == (int)CodeTypeEnum.PrePaid);

      }
</pre>
<p>What I didn&#8217;t expect was that the second refining, which I meant to happen to the result set in memory, actually spawned another query in the database.  Once I realized this it made sense, since the DataProvider for the IQueryable I was working with was the LLBL Gen Pro Implementation, and it is supposed to query against the database.   To do what I intended I converted the result set to a List before doing my refining which allowed the DataProvider to be the DataProvider underpinning LinqToObjects.  This then did what I wanted and queried against the data in memory.</p>
<pre class="brush: csharp;">

//--query against IQueryable that is LLBL Entity
var codesFromDB = from c in companyQ
                 where c.CompanyID == companyID
                 select c.PromoCodes;

//--convert to list based Queryable so
//   further refining done in memory

var codes = codesFromDB.ToList().AsQueryable();

if (codes.Count() &gt; 0)
            {
               //--get the freetrial from result set
                var freeTrial = codes.Where(c =&gt; c.CodeType == (int)CodeTypeEnum.FreeTrial).SingleOrDefault();

              //--get list prepaid from result set
                var prePaids = codes.Where(c =&gt; c.CodeType == (int)CodeTypeEnum.PrePaid);

      }
</pre>
<p>The lesson I learned here was keep in mind who owns an IQueryable or IEnumerable when using it, or you might end up with some unexpected side effects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=432</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handling AJAX Page Method Server Errors</title>
		<link>http://www.binzley.net/?p=423</link>
		<comments>http://www.binzley.net/?p=423#comments</comments>
		<pubDate>Fri, 30 Apr 2010 16:51:16 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[errorhandling]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[pagemethods]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=423</guid>
		<description><![CDATA[On my project we make use of jQuery to make AJAX calls to our web server.  On the server we use aspnet page methods to serve data to our jQuery AJAX calls and process updates sent from jQuery.  One interesting aspect of this is error handling.
Since we want to avoid any leakage of [...]]]></description>
			<content:encoded><![CDATA[<p>On my project we make use of jQuery to make AJAX calls to our web server.  On the server we use aspnet page methods to serve data to our jQuery AJAX calls and process updates sent from jQuery.  One interesting aspect of this is error handling.</p>
<p>Since we want to avoid any leakage of application information in the case of an error, we&#8217;ve taken the approach of putting a try/catch block around all functionality in a page method.  In the case of an error we log the original error and then throw a friendly exception so the jQuery AJAX caller knows something has gone wrong, but get no exception detail.  Here&#8217;s an example:</p>
<pre class="brush: csharp;">
[WebMethod]
        public static string SaveCustomerInformation(string customerID,
                                                string customerCode,
                                                string reasonForCall,
                                                string description)
        {
            string returnValue = string.Empty;
            try
            {
                bool isValidcustomerCode = true;
                customerCode = customerCode.Trim();

                //--validate input data
                if (!string.IsNullOrEmpty(customerCode) &amp;&amp; (customerCode.Length &lt; 3 || customerCode.Length &gt; 15))
                {
                   throw new WebMethodException(Content.ReusableContentHelper.customer_CODE_LENGTH_ERROR);
                }
                else if (!string.IsNullOrEmpty(customerCode) &amp;&amp; customerCode.ToLower().Equals(customerCodeLoginHelper.SERVICE_REQUEST_customer_CODE))
                {
                    throw new WebMethodException(Content.ReusableContentHelper.customer_CODE_CANNOT_USE_REQUESTED_ERROR);
                }
                //--End Validation

                //--Do Work
                CustomerImpl customerImpl = new customerImpl()
                {
                    customerID = int.Parse(JavaScriptHelper.DecryptValueAndHtmlDecode(customerID)),
                    customerCode = customerCode,
                    customerName = reasonForCall,
                    customerDescription = description
                };

                Factory.GetCustomerServices().SavecustomerInformation(customerImpl, currentUser);
                //--End Work                

            }
           catch (Exception e)
          {
               //--Log Exception
                Logger().LogException(e, ErrorLogImpl.ApplicationTypeEnum.Website, RidgeTool.BusinessInterfaces.Enums.SeverityLevelEnum.Error, HttpContext.Current.Request.Url.PathAndQuery, &quot;customer.SavecustomerInformation()&quot;, currentUser);
               //--Throw Friendly To Caller
                throw new WebMethodException(&quot;An error occured in SaveCustomerInformation&quot;);
          }
          return returnValue;
        }
</pre>
<p>In our javascript we wrap all AJAX calls in a common method allowing callers to provide a method to handle processing if an error occurs, and if no error handler is passed then an common error handling routine is run showing an alert box telling the user a problem has occurred.  Here&#8217;s what our jQuery AJAX call wrapper looks like.</p>
<pre class="brush: jscript;">
function AJAXCall(url, data, successCallBackFunction, errorCallBackFunction, completeCallBackFunction)
{
    data = JSON.stringify(data, UndefinedValueCheck);

    $.ajax({
        type: &quot;POST&quot;,
        url: url,
        data: data,
        contentType: &quot;application/json; charset=utf-8&quot;,
        dataType: &quot;json&quot;,
        error: function(xhr, status, exception)
        {
            var err = eval(&quot;(&quot; + xhr.responseText + &quot;)&quot;);
            if (errorCallBackFunction != null)
            {
                errorCallBackFunction(err.Message);
            }
            else
            {
                alert(err.Message);
            }
        },
        success: function(result)
        {
            if(successCallBackFunction != null)
            {
                //--eliminates .d from return values
                if (result.d != null)
                {
                    successCallBackFunction(result.d);
                }
                else
                {
                    successCallBackFunction(result);
                }
            }
        },
        complete: function()
        {
            if(completeCallBackFunction != null)
            {
                completeCallBackFunction();
            }
        }
    });
}
</pre>
<p>As you can see the user can choose to provide or not provide an error handling function and if they don&#8217;t user still is alerted a problem has occurred.</p>
<p>Here&#8217;s an example of our jQuery AJAX wrapper in use:</p>
<pre class="brush: jscript;">
 var text = $(&quot;#testingJavascriptTextBox&quot;).val();
            var passedData = &quot;{'testString': '&quot; + replaceForJavascript(text) + &quot;'}&quot;;
            var postData = new Object();
            postData.testString = text;

            AJAXCall(&quot;/WebMethods/Tags.aspx/TestingReplace&quot;, postData, function(textInput)
            {
                alert(textInput.d);
                $(&quot;#testingJavascriptSpan&quot;).append(replaceForHTML(textInput.d));
                $(&quot;#resultsJavascriptTextBox&quot;).attr(&quot;value&quot;, textInput.d);
            });
</pre>
<p>What all this means is that we protect ourselves form leaking application details in errors by never allowing a naked error to pass through an AJAX call to our web clients.  We still alert our AJAX caller to the existence of an error, so we can still know on the rare occasion (hopefully) when one happens!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=423</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependency Injection And Javascript</title>
		<link>http://www.binzley.net/?p=402</link>
		<comments>http://www.binzley.net/?p=402#comments</comments>
		<pubDate>Sun, 14 Mar 2010 20:13:24 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[dip]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=402</guid>
		<description><![CDATA[As we move towards a more unit tested and designed approach to our javascript code we&#8217;ve been playing with the notion of using dependency injection to allow us to abstract and allow mocking of javascript AJAX server calls.  What we&#8217;ve done is create a javascript object that handles making AJAX server calls.  The [...]]]></description>
			<content:encoded><![CDATA[<p>As we move towards a more unit tested and designed approach to our javascript code we&#8217;ve been playing with the notion of using dependency injection to allow us to abstract and allow mocking of javascript AJAX server calls.  What we&#8217;ve done is create a javascript object that handles making AJAX server calls.  The AJAX server call object has one method that takes a url, data to post, a success function handler, and an error function handler.  </p>
<pre class="brush: jscript;">
//definition of our real AJAX Server Caller
function AJAXServerCaller()
{
      //this created public method that can be called by our code
      this.MakeServerCall = function(url, data, successHandler, errorHandler)
     {
      var dataCleaned = JSON.stringify(data);
    $.ajax({
           type: &quot;POST&quot;,
           url: url,
           data: dataCleaned,
           contentType: &quot;application/json; charset=utf-8&quot;,
           dataType: &quot;json&quot;,
           success: successHandler(result.d),
           error:function (xhr, ajaxOptions, thrownError){
                   if(errorHandler != null)
                        errorHandler(thrownError);
                   else
                        alert('An Error Has Occurred');
                }
        });

    }

}
</pre>
<p>We house our server caller object in a AJAXServerCaller.js file, and this file is included when any calls are made that use the object to make an AJAX server call in their javascript.  In order to make an AJAX Server call an instance of the AJAX server calling object is passed in to a method as a parameter.  </p>
<pre class="brush: jscript;">
//example usage of ajax server caller

//function to handle successful return of AJAX call
function UpdateCustomerSaved(serverData)
{
      ///...do something to UI after ajax call completes successfully

}

//function to handle error result of AJAX call
function DisplayErrorCustomerSave(errorData)
{
      ///...do something to UI to notify of error
}

function SaveCustomerData(customerData, ajaxServerCaller)
{
        //acutual AJAX processing handed off to our server caller object
        ajaxServerCaller.MakeServerCall('http://portal/customerSave.aspx?SaveCustomer', customerData, UpdateCustomerSaved, DisplayErrorCustomerSave);
}

///Click Handler calls save method, creates and passes in server caller instance
function CustomerSaveClickHandler(event)
{
       var data = GetCustomerData();
       SaveCustomerData(data, new AJAXServerCaller());
}
</pre>
<p>When we&#8217;re testing any javascript that uses our AJAX server call object we simply include a file called &#8216;AJAXServerCallerMock.js&#8217; that has an object that has the exact same signature as our real AJAX server calling object, but has an extra property for fake data to be returned by a service call.  When testing the instance that is created is now of our mock AJAX server caller and javascript logic that relies on server calls can now be tested without actually hitting a server.</p>
<pre class="brush: jscript;">
//definition of our mock AJAX Server Caller, must have same object name and
//also the MakeServerCall method defined to act in place of real object
function AJAXServerCaller()
{
     //properties to hold fake data to return
     //and indexes so can do multiple calls in one test
     this.SuccessResultDataArray = new Array();
     var usedMockSuccessResultIndex = 0;

     //we'll allow an error to be programmed on a specific call
     this.ErrorOnCall = 0;
     this.ErrorResultData = null;
     var totalCallCount = 0;

      //this created public method will fake real server call, pass back preprogrammed data.
      this.MakeServerCall = function(url, data, successHandler, errorHandler)
      {
         totalCallCount++;
         // act as if error returned if programmed to do so
         if(this.ErrorOnCall == totalCallCount)
         {
             if(this.SuccessResultDataArray.length&lt;=usedMockSuccessResultIndex)
              {
                  errorHandler(this.ErrorResultData);
              }
         }
         //call success method with data matched to  index of call
         //and increment method call index.
         else
         {
              if(this.SuccessResultDataArray.length&lt;=usedMockSuccessResultIndex)
              {
                  successHandler(this.SuccessResultDataArray[usedMockSuccessResultIndex]);
                  usedMockSuccessResultIndex++;
              }
             else
              {
                  throw 'no success data available at index:' + usedMockSuccessResultIndex;
               }

            }
         });

    }

}
</pre>
<p>One issue with our approach is that our mock AJAX server call in testing is not exactly like the real AJAX call would be since the mock object is not asynchronous.  Our mock caller simply fires the functions passed to handle the ajax server result with the programmed mocked return data.  This hasn&#8217;t been a large issue, but might be problematic down the line.  Another issue could also arise if we need to support complex return scenarios with our mock, like multiple return values, or checking the number of calls made.  We will have to build a more complicated mock AJAX caller if we run into situations that require more complex mock object programming.</p>
<pre class="brush: jscript;">
//example testing using QUnit taking advantage of ajax server caller

var glbSuccess = false;

//function to handle successful return of AJAX call
function UpdateCustomerSaved(serverData)
{
      glbSuccess = true;

}

test(&quot;Test Save Customer Data calls server&quot;, function() {

    // -- if AJAXServerCallerMock.js is included for test this should be our mock
    var ajaxCaller = new AJAXServerCaller();

     //-- program mock return value for one expected call
    ajaxCaller.SuccessResultDataArray[0] = &quot;{result:0}&quot;;

     //--Act
     SaveCustomerData(data, ajaxCaller);

    //--Assert - check everything ok with ui.
    ok(methodToCheckCustomerInGoodState());
});
</pre>
<p>Between unit testing and adding dependency injection into our javascript it&#8217;s already beginning to look and feel a lot more organized.  My hope is this will allow us to produce higher quality javascript code, in less overall time.  We shall see! </p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=402</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Javascript</title>
		<link>http://www.binzley.net/?p=389</link>
		<comments>http://www.binzley.net/?p=389#comments</comments>
		<pubDate>Sat, 27 Feb 2010 16:26:57 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[qunit]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=389</guid>
		<description><![CDATA[Recently the project I&#8217;ve been working on has been moving more and more towards client side javascript, especially using jQuery.  We have been pretty consistent on the server side, especially in our business logic, in creating unit tests. We have over 1,000 unit tests in our business tier leveraging nUnit and Rhino Mocks, that [...]]]></description>
			<content:encoded><![CDATA[<p>Recently the project I&#8217;ve been working on has been moving more and more towards client side javascript, especially using <a title="jQuery" href="http://jquery.com/">jQuery</a>.  We have been pretty consistent on the server side, especially in our business logic, in creating unit tests. We have over 1,000 unit tests in our business tier leveraging <a title="nUnit" href="http://www.nunit.com/index.php">nUnit</a> and <a title="Rhino Mocks" href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a>, that are run every time a check in is done using <a title="Cruise Control" href="http://cruisecontrol.sourceforge.net/">Cruise Control</a> for continuous integration.  Pretty standard stuff for server side logic.</p>
<p>Since we are using more and more javascript why not reap the quality benefits of good unit test coverage here as well?  Considering javascript is non-typed and allows the running of strings as code through the &#8216;eval&#8217; function it would seem even more important to have good unit test coverage of our javascript.  Up to now we&#8217;ve ignored it since it&#8217;s been considered UI and not really logic.  With more and more ajax integration this no longer seems like a good practice.</p>
<p>For jQuery driven functionality we have been using the jQuery <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options">$.ajax</a> method to call down to asp.net pagemethods located  in web forms we created to support the jQuery functionality.   ASP.net pagemethods are essentially webservice calls located in a webform.  The calls have to be static and must be decorated with the [Webmethod] attribute.   Here is a great <a href="http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/">blog post</a> going into great detail about exactly how to call an ASP.net pagemethod from jQuery.  We essentially are doing the same thing.  We&#8217;ve actually wrapped our $.ajax call so we can centralize error handling and abstract away the &#8216;.d&#8217; return value you get when the pagemethod does it&#8217;s json serialization.</p>
<p>This post is about testing, however, so enough with how we&#8217;re using jQuery ajax.   From a testing perspetive what we wanted to be able to do was achieve the same test coverage in our jQuery and javascript as we have on our server side logic.   A little googling and what did I find, but <a title="qUnit" href="http://docs.jquery.com/QUnit">qUnit</a>!  The motif is almost the same as writing tests for nUnit, and when you run your tests qUnit provides default css so test results are shown in a html page in a very similar manner to how the nUnit client shows it&#8217;s test results.</p>
<p>The great thing is how easy this is to accomplish.  All you need to do is write tests in a .js file that exercise the code you wish to test using the qUnit syntax.  Then in a html page include jQuery, qUnit, the code you are testing and your test code.  In the html provide the nodes that qUnit will want to write to and, you&#8217;re done.   Here&#8217;s a very simple html example:</p>
<pre class="brush: xml;">
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; &gt;
   &lt;head&gt;
      &lt;title&gt;QUnit Test Example&lt;/title&gt;
        &lt;!-- css from qUnit to make output look good --&gt;
          &lt;link rel=&quot;stylesheet&quot; href=&quot;http://github.com/jquery/qunit/raw/master/qunit/qunit.css&quot; type=&quot;text/css&quot; media=&quot;screen&quot;&gt;
     &lt;!-- jQuery and qUnit include --&gt;
       &lt;script type=&quot;text/javascript&quot; src=&quot;/scripts/jquery-1.4.1.js&quot; &gt;&lt;/script&gt;
       &lt;script type=&quot;text/javascript&quot; src=&quot;http://github.com/jquery/qunit/raw/master/qunit/qunit.js&quot;&gt;&lt;/script&gt;
        &lt;!-- javascript you are testing include --&gt;
       &lt;script type=&quot;text/javascript&quot; src=&quot;/scripts/ControlScript.js&quot;&gt;&lt;/script&gt;
        &lt;!-- tests you wrote include --&gt;
       &lt;script type=&quot;text/javascript&quot; src=&quot;/scripts/ControlScriptTests.js&quot;&gt;&lt;/script&gt;
   &lt;/head&gt;
  &lt;!-- nodes qUnit will write to --&gt;
   &lt;body&gt;
       &lt;h1 id=&quot;qunit-header&quot;&gt;QUnit Test Suite&lt;/h1&gt;
       &lt;h2 id=&quot;qunit-banner&quot;&gt;&lt;/h2&gt;
       &lt;div id=&quot;qunit-testrunner-toolbar&quot;&gt;&lt;/div&gt;
       &lt;h2 id=&quot;qunit-userAgent&quot;&gt;&lt;/h2&gt;
       &lt;ol id=&quot;qunit-tests&quot;&gt;&lt;/ol&gt;
   &lt;/body&gt;
   &lt;/html&gt;
</pre>
<p>Very code I&#8217;m testing:</p>
<pre class="brush: jscript;">
function SetupButton(buttonID, txtBoxID, displayText)
      {
         $(&quot;#&quot; + buttonID).click(function() {
                  $(&quot;#&quot; + txtBoxID).attr(&quot;value&quot;, $(&quot;#&quot; + txtBoxID).attr(&quot;value&quot;) + ' ' + displayText);

            });
     }
</pre>
<p>And here are the tests I&#8217;m running:</p>
<pre class="brush: jscript;">
test(&quot;SetupButtonTest()&quot;, function() {

    var btn = document.createElement(&quot;input&quot;);
    btn.id = &quot;btn&quot;;

    btn.type = &quot;button&quot;;
    document.appendChild(btn);

    var txt = document.createElement(&quot;input&quot;);
    txt.id = &quot;txt&quot;;
    txt.type = &quot;text&quot;;
    document.appendChild(txt);

    SetupButton(&quot;btn&quot;, &quot;txt&quot;, &quot;disp&quot;);
    $(&quot;#btn&quot;).click();
    equals($(&quot;#txt&quot;).attr(&quot;value&quot;), &quot; disp&quot;, &quot;text box has display value: &quot; + $(&quot;#txt&quot;).attr(&quot;value&quot;));

})

test(&quot;SetupButtonTest2()&quot;, function() {

    var btn = document.createElement(&quot;input&quot;);
    btn.id = &quot;btn&quot;;

    btn.type = &quot;button&quot;;
    document.appendChild(btn);

    var txt = document.createElement(&quot;input&quot;);
    txt.id = &quot;txt&quot;;
    txt.type = &quot;text&quot;;
    document.appendChild(txt);

    SetupButton(&quot;btn&quot;, &quot;txt&quot;, &quot;disp&quot;);
    $(&quot;#btn&quot;).click();
    equals($(&quot;#txt&quot;).attr(&quot;value&quot;), &quot;disp&quot;, &quot;text box has display value: &quot; + $(&quot;#txt&quot;).attr(&quot;value&quot;));

})
</pre>
<p>As you can see qUnit provides a pretty straightforward way to unit test the now more complex javascript we&#8217;re writing in our project (the above is just an example, not actual code from our project).   The next step is to integrate qUnit into our continuous integration.  We would like to have our javascript tests run with every check in, just like our server side tests do.  Here is a <a title="qUnit CI" href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2008/09/18/running-jquery-qunit-tests-under-continuous-integration.aspx">post</a> on how to do it, it&#8217;s seems a little complicated.  I will give it a try and put up a post as to the results.</p>
<p>Hopefully we will be able to bring the benefites of good unit testing coverage out from just our server code and now apply it to the more and more complex client side code we&#8217;re creating.  After all why would it not be good practice to test code just because it&#8217;s javascript?  It seems even more important to test in a language that is non-typed and allows run-time execution of strings as code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=389</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CodeMash 2010 Wrap UP</title>
		<link>http://www.binzley.net/?p=380</link>
		<comments>http://www.binzley.net/?p=380#comments</comments>
		<pubDate>Mon, 18 Jan 2010 17:31:50 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[General Stuff]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=380</guid>
		<description><![CDATA[I attended CodeMash at Kalahri in Sandusky, Ohio last Wednesday and Thursday.  I skipped out on the last day to catch up on some work.  All in all it was a great experience.  I learned quite a bit and also felt validated in many of the approaches we&#8217;ve been taking at work.
Below are my notes [...]]]></description>
			<content:encoded><![CDATA[<p>I attended <a href="http://codemash.org/">CodeMash</a> at<a href="http://www.kalahariresorts.com/oh/"> Kalahri</a> in Sandusky, Ohio last Wednesday and Thursday.  I skipped out on the last day to catch up on some work.  All in all it was a great experience.  I learned quite a bit and also felt validated in many of the approaches we&#8217;ve been taking at work.</p>
<p>Below are my notes from the sessions I attended.  I also have to note my favorite quote from CodeMash.  Barry Hawkins was giving a presentation on Domain Driven Design.  When trying to describe the experience of talking to Doman Driven Design people about Domain Driven Design, (apparently they can be long winded in their explanations)  he said something like, &#8220;it&#8217;s like talking to <a href="http://en.wikipedia.org/wiki/Ent">Ents</a> with crack pipes&#8221;.  I liked that description a lot!</p>
<p>Session Notes:</p>
<p><a href="http://www.binzley.net/?p=359">Engineering Vs Design</a></p>
<p><a href="http://www.binzley.net/?p=356">Domain Driven Design</a></p>
<p><a href="http://www.binzley.net/?p=330">Software Design and Testablity</a></p>
<p><a href="http://www.binzley.net/?p=311">User Stories Closing The Agile Loop</a></p>
<p><a href="http://www.binzley.net/?p=305">Keynote &#8211; Lean Methodology</a></p>
<p><a href="http://www.binzley.net/?p=288">Agile &#8211; Iteration Zero</a></p>
<p><a rel="bookmark" href="http://www.binzley.net/?p=266">Practical B/TDD</a></p>
<p><a rel="bookmark" href="http://www.binzley.net/?p=252"> Fundamentals Of Software Engineering</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=380</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CodeMash &#8211; Engineering Vs Design</title>
		<link>http://www.binzley.net/?p=359</link>
		<comments>http://www.binzley.net/?p=359#comments</comments>
		<pubDate>Thu, 14 Jan 2010 21:58:40 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[General Stuff]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=359</guid>
		<description><![CDATA[It&#8217;s my last session today and forever at CodeMash this year.  I&#8217;m not able to show tomorrow.  Currently sitting in on Engineering Vs Design, given by Joe Nuxoll.
Reviewing Web 2.0 and RIA&#8217;s, things like Google Maps, could they have been envisioned by a designer with no software knowledge or vice versa?  Probably not.  Must have [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s my last session today and forever at <a href="http://codemash.org/">CodeMash</a> this year.  I&#8217;m not able to show tomorrow.  Currently sitting in on <a href="http://www.codemash.org/Sessions#Engineering+vs+Design+-+How+to+work+together">Engineering Vs Design</a>, given by <a href="http://joeracer.blogspot.com/">Joe Nuxoll</a>.</p>
<p>Reviewing <a href="http://en.wikipedia.org/wiki/Web_2.0">Web 2.0</a> and <a href="http://en.wikipedia.org/wiki/Rich_Internet_application">RIA</a>&#8217;s, things like Google Maps, could they have been envisioned by a designer with no software knowledge or vice versa?  Probably not.  Must have design and engineering mixed together in ways not previously needed.  UI Engineering is design and design is UI Engineering.</p>
<p>Traditional Roles in product development: Designers, UI Developers, and web UI developers.  More and more you are seeing people who can do all of these tasks as need to understand them all.  New breed of tools to simplify this sort of work, RIA Design tools:  <a href="http://labs.adobe.com/technologies/flashcatalyst/">Adobe Catalyst</a>, <a href="http://javafx.com/docs/gettingstarted/production_suite/">JavaFX Production Suite</a>.</p>
<p>Important to cross train engineers and designers as they function with very different processes.  Important to educate engineers on the design process and designers on the engineering process to encourage mutual skill appreciation.  To this end co-location is very helpful.  Much easier for designers and engineers to understand and support each others processes if they are situated together.</p>
<p>Important to understand the difference between prototype and production.  Build many prototypes and be willing to throw them away.  Joe likes to use a separate folder in subversion for design, partly because subversion is good at handling design type resources and partly to separate highly iterative resources.   The design folder is prototype work, not production.  Also brings benefit of version control to design, where it is not traditionally used.</p>
<p>Build detailed facades.  These are generally not going to be production code, be ready to throw much of it away.  Really iterate to get it right.  Stub out back end calls and keep back end people in the loop.  Make sure the UI team has regular check ins with the back end team.</p>
<p>Once you&#8217;ve iterated to the point where can start work on production code can lift much of the final iteratino prototype code to start production work.  Keep prototypes clean by doing production work in separate source control folder.</p>
<p>Joe seems to be wrapping up although still 20 minutes left in the session.  I think we&#8217;re going to Question and Answer now.  Question came up as to how to get end users to not focus on color and such when reviewing a functional wire frame?  Joe&#8217;s answer, keep all design detail out of functional wireframe so nothing for end user to get distracted by.</p>
<p>Wire frame prototyping should happen before visual design.  Designers need app functionality to be fairly solid before they can effectively begin their work.  Interaction and functionality should be defined thoroughly before visual design.</p>
<p>Well that&#8217;s a wrap.  Another good session, not very technical but very relevant to our current work.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=359</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>CodeMash &#8211; Domain Driven Design</title>
		<link>http://www.binzley.net/?p=356</link>
		<comments>http://www.binzley.net/?p=356#comments</comments>
		<pubDate>Thu, 14 Jan 2010 21:51:55 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[General Stuff]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=356</guid>
		<description><![CDATA[Time for the second afternoon session here at CodeMash.  This session is called Domain Driven Design  and is being given by a gentleman by the name of Barry Hawkins.  This is the second presentation I&#8217;ve seen Barry give today, he&#8217;s a very dynamica and entertaining speaker, but still is very on point.
The presentation focused [...]]]></description>
			<content:encoded><![CDATA[<p>Time for the second afternoon session here at <a href="http://codemash.org/">CodeMash</a>.  This session is called <a href="http://www.codemash.org/Sessions#Domain-Driven+Design%3a+An+Introduction">Domain Driven Design</a> <a href="http://www.codemash.org/Sessions#User+Stories%3a+Closing+the+Agile+Loop"></a> and is being given by a gentleman by the name of <a href="http://www.alltc.com/">Barry Hawkins</a>.  This is the second presentation I&#8217;ve seen Barry give today, he&#8217;s a very dynamica and entertaining speaker, but still is very on point.</p>
<p>The presentation focused on the importance of modeling.  To distill this greatly models are a representation of the domain, the domain is the subject matter itself.  It is important to use ubiquitous language across a team made up of all people necessary to move project from conception to completion.  This means that subject matter experts and scenarios they provide feed the domain vocabulary, not pattern and practice leanings.</p>
<p>Domain models should start small and be validated by detailed reference scenarios.  Barry&#8217;s team uses nNuit or jUnit to create tests to in effect &#8216;model&#8217; the reference scenarios so they can validate the model accurately reflects them.  The reference scenarios get increasingly complicated and are provided by domain subject matter experts.  Barry used an example from the shipping industry as an example.</p>
<p>Another importance concept was to entertain different models, don&#8217;t settle on the first solution you think of.  Use natural language to pseudo code out multiple modeling options to decide which is best for the context you&#8217;re in.  Don&#8217;t be afraid to throw out models if they don&#8217;t work, the first thing isn&#8217;t the best thing necessarily.</p>
<p>Barry works with Eric Evans who authored a book, <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain Driven Design</a>, which the talk was based on.  Great overview of a very deep topic.  I&#8217;m looking forward to picking up the book and learning more.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=356</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>CodeMash &#8211; Software Design and Testablity</title>
		<link>http://www.binzley.net/?p=330</link>
		<comments>http://www.binzley.net/?p=330#comments</comments>
		<pubDate>Thu, 14 Jan 2010 18:45:09 +0000</pubDate>
		<dc:creator>Robert Binzley</dc:creator>
				<category><![CDATA[General Stuff]]></category>

		<guid isPermaLink="false">http://www.binzley.net/?p=330</guid>
		<description><![CDATA[It&#8217;s Thursday afternoon here now at CodeMash.  Had a nice lunch while listening to a presentation on Microsoft&#8217;s open source efforts given by Hank Janssen. Now I&#8217;m sitting in on my first afternoon session, Software Design and Testability, the presentation is being given by Jeremy Miller, a gentleman from Dovetail Software in Austin Texas.
Testability and [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s Thursday afternoon here now at <a href="http://codemash.org/">CodeMash</a>.  Had a nice lunch while listening to a presentation on Microsoft&#8217;s open source efforts given by <a href="http://port25.technet.com/archive/tags/Hank+Janssen/default.aspx">Hank Janssen.</a> Now I&#8217;m sitting in on my first afternoon session, <a href="http://www.codemash.org/Sessions#Software+Design+and+Testability">Software Design and Testability</a>, the presentation is being given by <a href="http://codebetter.com/blogs/jeremy.miller/">Jeremy Miller</a>, a gentleman from <a href="http://www.dovetailsoftware.com/">Dovetail Software</a> in Austin Texas.</p>
<p>Testability and Design &#8230;is about finding, removing and preventing defects&#8230;.is about assiging and partitioning responsibilities in an application&#8230;corresponds well to traditionally good design ideas&#8230;..is facilitated by patterns.</p>
<p>Need to shift mindset, I don&#8217;t write code, I ship software&#8230;.people should see their efforts in the context of the whole, testability promotes this.  Software isn&#8217;t designed for the efficiency and optimzation of the code itself, but for the software as a whole.   Good code is only important in that it enables us to delivery what the customer wants, where it does not do that it doesn&#8217;t really matter.  That being said it is really important since good code allows software to be changed and worked on by other developers more easily, allowing us to better deliver wanted features to our customers.</p>
<p>First Causes Of Good Design: Fast feedback, short iterations are important to good design (agile)&#8230;&#8230;Orthogonality, good separation of concerns (persistence, ui) so changes can be kept to small parts of the system when made.  Changes will be needed when made only want to change one area of system to accommodate.  This allows you to change things more easily when you know more later in your project.   You will be wrong at times, this helps make things easier to change to accommodate this&#8230;&#8230;&#8230;&#8230;Reversibility, give customers the ability to change their mind&#8230;&#8230;&#8230;&#8230;.Understandability, although smaller classes for testing that interact more may make things less understandable.</p>
<p>Writing Automated Tests:  Known Inputs and Measurable Outcomes.  State Based tests versus Interaction Based tests, state based tests check to see if state changes occurred appropriately, testing to see if something else was called appropriately are interaction based tests (mock objects).</p>
<p>What makes a good test?  Repeatable&#8230;..Run Fast&#8230;..Easy To Write&#8230;.Easy To Understand, a good test tells you where and why it failed, not just that it failed.</p>
<p>Jeremy is pulling up an example of something he did early on that was not testable.  Showing us the actual code.  Example code is doing many things at once, hitting database and doing processing.  Code is impossible to test without setting up entire application.</p>
<p>You should isolate the ugly stuff, isolate external dependencies ie the database, active directory, remoting, chatty api&#8217;s, etc&#8230;..etc&#8230;&#8230;  Jeremy gave an example from <a href="http://jayflowers.com/joomla/">Jay Flowers</a>, <a href="http://jayflowers.com/joomla/index.php?option=com_content&amp;task=view&amp;id=31">Expand The Creamy Center</a>.   Jeremy is now walking through how to do this with the sample bad code he has up on the screen.   Refactoring code into state machine that is heart of the workflow, ugly stuff is pulled out and state machine is tested using mocks for the ugly stuff.</p>
<p>Coding from the bottom up is good idea.  Test small to begin with, then test big.  Don&#8217;t try and put everything together and then test, hard to find problems you find.  Build little things at a time and assemble them.  Jeremy is a big fan of <a href="http://msdn.microsoft.com/en-us/magazine/cc721605.aspx">Object Role Stereotypes</a> and <a href="http://c2.com/cgi/wiki?ResponsibilityDrivenDesign">responsiblity driven design</a>, this is in the context of introducing a controller into his refactoring of his example code.</p>
<p>Inversion of control discussion.  Should push not pull, if your class is directly accessing a config file or database it is very tightly coupled to these things and hard to test.  Push externally needed things into your classes so they aren&#8217;t coupled to these items.  Push don&#8217;t pull!  This also causes you to keep a short tail, can resuse code without needing a whole lot of other code to come with it.</p>
<p>The hour is up, a very good presentation I thought.  The push versus pull analogy really made a lot of sense a clarified why we&#8217;re doing a lot of the things we&#8217;re doing.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.binzley.net/?feed=rss2&amp;p=330</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
