<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>K. Scott Allen</title><link>http://odetocode.com/Blogs/scott/default.aspx</link><description>Experiments in writing</description><dc:language>en-US</dc:language><generator>CommunityServer 1.1 (Build: 1.1.0.50615)</generator><item><title>Pretty Code #1 – Building SelectListItems</title><link>http://odetocode.com/Blogs/scott/archive/2009/07/02/13170.aspx</link><pubDate>Fri, 03 Jul 2009 04:11:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:13170</guid><dc:creator>scott</dc:creator><slash:comments>2</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/13170.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=13170</wfw:commentRss><description>&lt;p&gt;In ASP.NET MVC, you can use a collection of &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.aspx" target="_blank"&gt;SelectListItem&lt;/a&gt;s to help build an HTML &amp;lt;select&amp;gt;. &lt;a href="http://blog.wekeroad.com/blog/asp-net-mvc-dropdownlist-and-html-attributes/" target="_blank"&gt;Just watch out for the HTML helper overloads&lt;/a&gt;. The question is – &lt;strong&gt;&lt;em&gt;what is the prettiest code that can change a list of Products into a collection of SelectListItems? &lt;/em&gt;&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Tonight, you’ll be the judge in this first contest of charm, grace, and readability.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Contestant #1&lt;/strong&gt; hails from the System.Web.Mvc namespace. It likes pina coladas and string literals, but is turned off by tattoos that look like programming symbols. Let me introduce the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist.aspx" target="_blank"&gt;SelectList&lt;/a&gt; class:&lt;/p&gt; &lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;products = GetProducts();
&lt;span style="color: blue;"&gt;var &lt;/span&gt;selectItems = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SelectList&lt;/span&gt;(products, &lt;span style="color: rgb(163, 21, 21);"&gt;"ID"&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;);
&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;Contestant #2&lt;/strong&gt; lives in the System.Linq namespace. It likes whips and method chains. Functional programmers call it “map”, but in .NET we call it "Select": &lt;br&gt;&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;selectItems = &lt;span style="color: blue;"&gt;from &lt;/span&gt;product &lt;span style="color: blue;"&gt;in &lt;/span&gt;GetProducts()
                  &lt;span style="color: blue;"&gt;select new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SelectListItem 
                  &lt;/span&gt;{
                      Text = product.Name,
                      Value = product.ID.ToString()
                  };
&lt;/pre&gt;
&lt;br&gt;… or (from the backside) … &lt;br&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;selectList = GetProducts().Select(product =&amp;gt;
                    &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;SelectListItem
                    &lt;/span&gt;{
                        Value = product.ID.ToString(),
                        Text = product.Name 
                    });
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Contestant #3&lt;/strong&gt; lives in the MvcContrib project. It’s turned on by pointy things and practices yoga for extensibility. Introducing the ToSelectList method:&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;selectItems = GetProducts().ToSelectList(product =&amp;gt; product.ID,
                                             product =&amp;gt; product.Name);
&lt;/pre&gt;
&lt;p&gt;Personally, I like #2. While the name of #3 makes its purpose obvious, it sometimes takes a moment to be 100% clear about what property becomes Text, and what property becomes Value. In #2 the Text and Value assignments are obvious, even though the code is a little longer. Setting the Selected properties with either approach is trivial. &lt;/p&gt;
&lt;p&gt;What do you think?&lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=13170" width="1" height="1"&gt;</description></item><item><title>Three IIS Concepts ASP.NET Developers Should Know</title><link>http://odetocode.com/Blogs/scott/archive/2009/07/01/13167.aspx</link><pubDate>Wed, 01 Jul 2009 23:37:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:13167</guid><dc:creator>scott</dc:creator><slash:comments>2</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/13167.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=13167</wfw:commentRss><description>    &lt;p&gt;
        It’s possible to do a lot of work with ASP.NET and not know &lt;i&gt;anything &lt;/i&gt;about IIS,
        particularly if you work with a large team where IT specialists keep the riff-raff
        away from production web applications. Ever since Visual Studio started shipping
its own web server&lt;sup&gt;1&lt;/sup&gt;, many people don’t rely on IIS for day
        to day development work (although many of us still do).
    &lt;/p&gt;
    &lt;p&gt;
        For those of you who are just learning how to deploy in IIS, or those of you who
        need a refresher, I put together a short and free Pluralsight screen cast on IIS: &lt;a href="http://www.pluralsight.com/main/screencasts/screencast.aspx?id=iis-aspnetdev" target="_blank"&gt;&lt;strong&gt;Web Sites, Applications, and Virtual Directories in IIS&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
    &lt;a href="http://www.pluralsight.com/main/screencasts/screencast.aspx?id=iis-aspnetdev" target="_blank"&gt;
        &lt;img title="This screencast demonstrates three essential concepts you should know to host web applications in Windows Internet Information Services." src="http://www.pluralsight.com/main/screencasts/images/iis-aspnetdev-300.jpg"&gt;&lt;/a&gt;
    &lt;p&gt;
        This is one video in a &lt;a href="http://www.pluralsight.com/main/screencasts/Default.aspx" target="_blank"&gt;collection of screencasts from Pluralsight&lt;/a&gt;.
    &lt;/p&gt;
    &lt;p&gt;
        &lt;font size="2"&gt;1) Some people call the web server “Cassini”. Other people call it the “WebDev”
        server. Still others call it “the web thingy that sits in my system tray”,
        even though Windows doesn’t have a &lt;a href="http://blogs.msdn.com/oldnewthing/archive/2003/09/10/54831.aspx" target="_blank"&gt;system tray&lt;/a&gt;, but whatever. If you worked with the first
        release of Visual Studio, you’ll know we’ve come a long way from running as an administrator
        with Front Page Extensions installed and the IDE trying to force all of our code
        to live underneath inetpub\wwwroot &amp;lt;shudder /&amp;gt;.
    &lt;/font&gt;&lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=13167" width="1" height="1"&gt;</description></item><item><title>Principles, Code-Behind, &amp;amp; View Engines</title><link>http://odetocode.com/Blogs/scott/archive/2009/06/29/13036.aspx</link><pubDate>Mon, 29 Jun 2009 08:10:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:13036</guid><dc:creator>scott</dc:creator><slash:comments>13</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/13036.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=13036</wfw:commentRss><description>&lt;p&gt;The July issue of MSDN Magazine is available online with my article “&lt;a href="http://msdn.microsoft.com/en-us/magazine/dd942822.aspx" target="_blank"&gt;Guiding Principles For Your ASP.NET MVC Applications&lt;/a&gt;”. Another MVC article in this issue is &lt;a href="http://www.codethinked.com/" target="_blank"&gt;Justin Etheredge&lt;/a&gt;’s “&lt;a href="http://msdn.microsoft.com/en-us/magazine/dd942838.aspx" target="_blank"&gt;Building Testable ASP.NET MVC Applications&lt;/a&gt;”. Justin’s article is a good one as he shows you how to design for testability, and includes specific examples with &lt;a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=xunit" target="_blank"&gt;xUnit.net&lt;/a&gt;, &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;moq&lt;/a&gt;, and &lt;a href="http://ninject.org/" target="_blank"&gt;Ninject&lt;/a&gt;. &lt;/p&gt; &lt;p&gt;Something we both touched on was the topic of code-behind files. &lt;/p&gt; &lt;h3&gt;Code-Behind and ASP.NET MVC&lt;/h3&gt; &lt;p&gt;The conversation between two developers (let’s call them Pushy and Principled), goes like this:&lt;a href="http://www.flickr.com/photos/hand-nor-glove/563304745/" target="_blank"&gt;&lt;img title="I WANT CODE-BEHIND!!" alt="I WANT CODE-BEHIND!!" src="http://www.odetocode.com/aimages/200906/argument_3.jpg" width="304" align="right" border="0" height="204"&gt;&lt;/a&gt; &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;strong&gt;Pushy&lt;/strong&gt;: Is it OK to use code-behind files with aspx views?&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Principled:&lt;/strong&gt; No.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Pushy&lt;/strong&gt;: But, I have something that’s really, really specific to this one particular view. That’s OK, right?&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Principled&lt;/strong&gt;: No. &lt;/p&gt; &lt;p&gt;&lt;strong&gt;Pushy&lt;/strong&gt;: Oh, come on! You aren’t being pragmatic here. I don’t want to add a Page_Load, I just need a teeny tiny little instance method. I’ll add a code-behind file and stick it inside. It’s tiny! That’s OK, right?&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Principled&lt;/strong&gt;: No. &lt;/p&gt; &lt;p&gt;&lt;strong&gt;Pushy&lt;/strong&gt;: Really now, what do you expect me to do? Build one of those forsakenly awful HTML helper methods with more overloads than the California power grid in August? Don’t you think it’s better to put the code close to the view that uses it?&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Principled&lt;/strong&gt;: No. &lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This is one scenario where I’d side with Principled. Sure, the code-behind could be simple. Sure, if you are careful it might even be unit-testable. But, the mere fact that code-behind is possible is a fluke and a byproduct from building on an existing framework. Someone writing an MVC view engine from scratch wouldn’t need to provide such a feature that allows you to put anything resembling intelligence near a view. &lt;/p&gt; &lt;p&gt;All of the problems I’ve seen described where code-behind is a solution could easily be solved with an HTML helper, or by using a more robust presentation model that is passed to the view. Some people worry about a proliferation of HTML helpers, but if you absolutely need a helper scoped to a specific view, you can always put the helper in a different namespace that only that particular view will use. &lt;/p&gt; &lt;p&gt;I know your team is disciplined. I know you wouldn’t do anything wrong. I know you want to be pragmatic and do the simplest thing that works. But, think of the first code-behind file in a project as the first &lt;a href="http://www.pragprog.com/the-pragmatic-programmer/extracts/software-entropy" target="_blank"&gt;broken window&lt;/a&gt;. It’s another degree of freedom where entropy can wiggle into your software and undermine maintainability. It’s making a view smarter, which your principles should suggest is wrong. &lt;br&gt;&lt;/p&gt;&lt;p&gt;Thoughts?&lt;br&gt;&lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=13036" width="1" height="1"&gt;</description></item><item><title>Functional Programming Battles GOTOzilla</title><link>http://odetocode.com/Blogs/scott/archive/2009/06/16/12911.aspx</link><pubDate>Wed, 17 Jun 2009 01:53:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12911</guid><dc:creator>scott</dc:creator><slash:comments>23</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12911.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12911</wfw:commentRss><description>&lt;p&gt;Steve Wellens had a recent blog post arguing for the use of a goto in C# (see: &lt;a href="http://weblogs.asp.net/stevewellens/archive/2009/06/01/why-goto-still-exists-in-c.aspx" target="_blank"&gt;Why goto Still Exists in C#&lt;/a&gt;). Steve had a series of methods he wants to execute, but he wants to stop if any given method returns false. At the end of the post, Steve decided that the following code with goto was better than setting boolean variables:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: green;"&gt;&lt;a href="http://www.flickr.com/photos/kaptainkobold/382081834/" target="_blank"&gt;&lt;img title="Functional programming battles the GOTO" alt="Functional programming battles the GOTO" src="http://www.odetocode.com/aimages/200906/godzillagamera_3.jpg" width="302" align="right" border="0" height="227"&gt;&lt;/a&gt; // DoProcess using goto
&lt;/span&gt;&lt;span style="color: blue;"&gt;void &lt;/span&gt;DoProcess3()
{
    LOG(&lt;span style="color: rgb(163, 21, 21);"&gt;"DoProcess Started..."&lt;/span&gt;);

    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(Step1() == &lt;span style="color: blue;"&gt;false&lt;/span&gt;)
        &lt;span style="color: blue;"&gt;goto &lt;/span&gt;EXIT;
    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(Step2() == &lt;span style="color: blue;"&gt;false&lt;/span&gt;)
        &lt;span style="color: blue;"&gt;goto &lt;/span&gt;EXIT;
    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(Step3() == &lt;span style="color: blue;"&gt;false&lt;/span&gt;)
        &lt;span style="color: blue;"&gt;goto &lt;/span&gt;EXIT;
    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(Step4() == &lt;span style="color: blue;"&gt;false&lt;/span&gt;)
        &lt;span style="color: blue;"&gt;goto &lt;/span&gt;EXIT;
    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(Step5() == &lt;span style="color: blue;"&gt;false&lt;/span&gt;)
        &lt;span style="color: blue;"&gt;goto &lt;/span&gt;EXIT;

EXIT:
    LOG(&lt;span style="color: rgb(163, 21, 21);"&gt;"DoProcess Finished"&lt;/span&gt;);
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;In the comments, a remark from a different Steve stood out. Steve suggested using an array of Func&amp;lt;bool&amp;gt;. The comment didn’t generate any further discussion, but it’s worthy to call out.&lt;/p&gt;
&lt;p&gt;I don’t think the problem with the above code is with the goto per-se. I think the problem is how the code conflates “what to do” with “how to do it”. In this scenario both are a little bit tricky. Let’s assume we might need to add, remove, or change the order of the method calls. But, the method calls are so intertwined with conditional checks and goto statements that it obscures the process. Using an array of Func&amp;lt;bool&amp;gt; is a simple approach, yet it still manages to create a data structure that &lt;em&gt;isolates&lt;/em&gt; “what to do”. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;void &lt;/span&gt;Process()
{
    &lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;bool&lt;/span&gt;&amp;gt;[] steps =
    {
        Step1,
        Step2,
        Step3,
        Step4,
        Step5
    };

    ExecuteStepsUntilFirstFailure(steps);
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;You could argue that all this code does is push the problem of “how to do it” further down the stack. That’s true, but we’ve still managed to separate “what” from “how”, and that’s a big win for maintaining this code. The simplest thing that could possibly work for “how” would be:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;void &lt;/span&gt;ExecuteStepsUntilFirstFailure(&lt;span style="color: rgb(43, 145, 175);"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt; steps)
{
    steps.All(step =&amp;gt; step() == &lt;span style="color: blue;"&gt;true&lt;/span&gt;);
}
&lt;/pre&gt;
&lt;p&gt;The All operator is documented as stopping as soon as a result can be determined, so the above code is equivalent to the following:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;void &lt;/span&gt;ExecuteStepsUntilFirstFailure(&lt;span style="color: rgb(43, 145, 175);"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43, 145, 175);"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt; steps)
{
    &lt;span style="color: blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue;"&gt;var &lt;/span&gt;step &lt;span style="color: blue;"&gt;in &lt;/span&gt;steps)
    {
        &lt;span style="color: blue;"&gt;if &lt;/span&gt;(step() == &lt;span style="color: blue;"&gt;false&lt;/span&gt;)
        {
            &lt;span style="color: blue;"&gt;break&lt;/span&gt;;
        }
    }&lt;/pre&gt;&lt;pre class="code"&gt;}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;With this approach it’s easy to change the order of the steps, or to add steps and delete steps, without worrying about missing a goto or conditional check. The next step up in complexity (excuse the pun) would be to create a Step class and encapsulate the Func with other metadata and state. I’m sure you could also imagine the execution phase relying on an IStepExector interface as the base for executing steps under a transaction, or with step-level logging, or even in parallel – and all this without changing how the steps are arranged. Take this to an extreme, and you’ll have a technology like Windows Workflow Foundation. :) &lt;/p&gt;
&lt;p&gt;The ability of functional and declarative programming to separate the “what” and the “how” is powerful, but you don’t need a new language, and you can start simple. In this scenario it’s another tool you can use to save your city from the goto-zilla monster. &lt;/p&gt;
&lt;p&gt;What do you think?&lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12911" width="1" height="1"&gt;</description></item><item><title>Progressive .NET Event In Stockholm</title><link>http://odetocode.com/Blogs/scott/archive/2009/06/10/12907.aspx</link><pubDate>Wed, 10 Jun 2009 08:49:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12907</guid><dc:creator>scott</dc:creator><slash:comments>2</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12907.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12907</wfw:commentRss><description>&lt;p&gt;Øredev is putting together an exciting lineup of topics and speakers for &lt;a href="http://518.nu/Prod/Oredev/site_net.nsf/" target="_blank"&gt;Progressive .NET Days&lt;/a&gt;. The event is August 27-28 in Stockholm Sweden. &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Progressive software development understands that tomorrow's better ideas for software development are likely here with us today and seeks them out now, building bridges that span paradigms through practice and experience. &lt;/p&gt;&lt;/blockquote&gt;  &lt;p&gt;I’m excited to be a part of the event, and wish I could also sit in on every other session.I’ve also had a dream to ride in a hot air balloon, which I understand is &lt;a href="http://away.com/top_picks/ballooning_2.html" target="_blank"&gt;quite popular&lt;/a&gt; during the summer months in Stockholm….&lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12907" width="1" height="1"&gt;</description></item><item><title>When Do I Use Interfaces?</title><link>http://odetocode.com/Blogs/scott/archive/2009/06/07/12891.aspx</link><pubDate>Mon, 08 Jun 2009 06:50:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12891</guid><dc:creator>scott</dc:creator><slash:comments>11</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12891.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12891</wfw:commentRss><description>&lt;p&gt;&lt;a href="http://www.flickr.com/photos/wocrig/3052628550/" target="_blank"&gt;&lt;img title="interface" alt="interface" src="http://www.odetocode.com/aimages/200906/interface_3.jpg" width="244" align="right" border="0" height="184"&gt;&lt;/a&gt; “Program to an interface, not an implementation” is a well-known mantra from the &lt;a href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612" target="_blank"&gt;GoF book&lt;/a&gt;. Take this guidance to an extreme, though, and you generate &lt;a href="http://www.codinghorror.com/blog/archives/000801.html" target="_blank"&gt;POO instead of OOP&lt;/a&gt;. How do know if you crossed the line?&lt;/p&gt; &lt;p&gt;I think it’s useful to take a step back and think about the word “interface” in a general sense. There are interfaces everywhere in software.&amp;nbsp; There are interfaces between layers, between tiers, between applications, between objects, and between callers and their callees. Just about anything and everything in software, no matter how trivial, has an interface. &lt;/p&gt; &lt;p&gt;The real question with interfaces is how many constraints you want in place for any given interface. Consider the following JavaScript code. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;function &lt;/span&gt;validate(creditService) {
    creditService.checkCreditForCustomer(&lt;span style="color: blue;"&gt;this&lt;/span&gt;.id);
}&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;The only constraint on the creditService parameter is that the object needs a checkCreditForCustomer function that takes an ID parameter. The validation function doesn’t care how the creditService was built, who built it, where it came from, or what other capabilities might be in place. This code demonstrates the flexible, dynamic, and relatively unconstrained qualities of &lt;a href="http://c2.com/cgi/wiki?DuckTyping" target="_blank"&gt;duck typing&lt;/a&gt;. If the parameter checks the credit of a customer like a credit service should, then it must be a credit service. &lt;/p&gt;
&lt;h3&gt;Going Static&lt;/h3&gt;
&lt;p&gt;Static languages generally have to crank up the constraints on an interface, although many have an escape hatch. C# 4.0, for example, introduces a &lt;a href="http://msdn.microsoft.com/en-us/library/dd264736%28VS.100%29.aspx" target="_blank"&gt;dynamic type&lt;/a&gt;. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public bool &lt;/span&gt;Validate(&lt;span style="color: blue;"&gt;dynamic &lt;/span&gt;creditService)
{
    &lt;span style="color: blue;"&gt;return &lt;/span&gt;creditService.CheckCreditForCustomer(ID);
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Again - all we need is an object with a CheckCreditForCustomer method that takes an int parameter. Because the object is typed as dynamic, the compiler won’t guarantee what the object can actually do – there is no type checking. At runtime, we may find out the object doesn’t actually support the method we are looking for, and an exception appears. This duck typing behavior is what keeps fans of static typing awake at night. They think the dynamic programmers are insane for throwing around objects in a willy-nilly manner. Meanwhile, the dynamic crowd thinks the fans of static typing are insane for spending all of their time obsessing over types instead of creating software. &lt;/p&gt;
&lt;p&gt;Regardless of where you fall in the static to dynamic spectrum, you can view a type definition as a constraint. In C# and Java, the &lt;em&gt;interface&lt;/em&gt; keyword can constrain the type of an object without placing any constraints on the implementation. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;interface &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ICreditService
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;bool &lt;/span&gt;CheckCreditForCustomer(&lt;span style="color: blue;"&gt;int &lt;/span&gt;id);
    &lt;span style="color: blue;"&gt;bool &lt;/span&gt;CheckCreditForCompany(&lt;span style="color: blue;"&gt;int &lt;/span&gt;id);
}
&lt;/pre&gt;
&lt;p&gt;Now we can use this constraint to enforce type safety. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public bool &lt;/span&gt;Validate(&lt;span style="color: rgb(43, 145, 175);"&gt;ICreditService &lt;/span&gt;creditService)
{
    &lt;span style="color: blue;"&gt;return &lt;/span&gt;creditService.CheckCreditForCustomer(ID);
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;An interface (in the &lt;em&gt;interface&lt;/em&gt; keyword sense) allows fans of static typing to sleep at night while still leaving some flexibility behind. The object that arrives as an ICreditService on any given call might be one of 10 different credit service implementations. The 10 implementations may be from the same class inheritance hierarchy, or they may not. One might be a mock object or test double used only during testing (which I should point out is &lt;em&gt;not, not, not&lt;/em&gt; the point of using interfaces), or it may not. The Validate doesn’t care about the concrete implementation behind the interface. &lt;/p&gt;
&lt;p&gt;We still have some flexibility, but we also have additional constraints when compared to duck typing. The credit service has to implement two methods now, even if we just want to build an object for the Validate method which only uses the CheckCreditForCustomer method. These two methods may or may not be good thing. Iterative design with tests and a dose of the &lt;a href="http://www.objectmentor.com/resources/articles/isp.pdf" target="_blank"&gt;interface segregation principle&lt;/a&gt; will take care of the matter. &lt;/p&gt;
&lt;h3&gt;Going Concrete&lt;/h3&gt;
&lt;p&gt;Even more constraints come into play if we use a class definition instead of an interface. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;CreditService
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;public virtual bool &lt;/span&gt;CheckCreditForCustomer(&lt;span style="color: blue;"&gt;int &lt;/span&gt;id)
    { 
        &lt;span style="color: green;"&gt;// ...
    &lt;/span&gt;}
    
    &lt;span style="color: green;"&gt;// ...
&lt;/span&gt;}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Now we’ve not only constrained the type, but we’ve constrained the implementation. Whoever provides our credit service functionality &lt;em&gt;must&lt;/em&gt; be a CreditService object, or use CreditService as a base class. Building software is all about composing pieces of functionality together, and using a concrete class as the interface specification places &lt;strong&gt;hard restrictions&lt;/strong&gt; on how the composition will work now,and in the future. &lt;/p&gt;
&lt;h3&gt;Interfaces Everywhere?&lt;/h3&gt;
&lt;p&gt;Sometimes, these hard restrictions make sense, or at least aren’t important. For example, classes that have no behavior (like DTOs) don’t need an interface abstraction. I’ve also never found it useful to specify entities using an interface, as they have pure business logic inside (logic dealing only with other business objects or abstractions). &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public interface &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ICustomer
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;int &lt;/span&gt;ID { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }          
    &lt;span style="color: blue;"&gt;int &lt;/span&gt;Name { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue;"&gt;void &lt;/span&gt;UpdateAddress(&lt;span style="color: green;"&gt;/* ... */&lt;/span&gt;);
    &lt;span style="color: green;"&gt;// ...
&lt;/span&gt;}&lt;/pre&gt;&lt;pre class="code"&gt;&amp;nbsp;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;In short, you don’t need interfaces &lt;em&gt;everywhere&lt;/em&gt;, you need to anticipate where your software needs to be flexible, which isn’t always easy. Using interface definitions between two horizontal or vertical layers of an application is almost always a yes, but programming to an interface between two business objects inside the same context is a definite maybe. &lt;/p&gt;
&lt;p&gt;I like to use interface definitions when I want to turn a detail into a concept. For example, I’d feel more comfortable with an business object using an ISendMessage object then an SmtpServer object. The concept is closer to what the object needs to do (send a message), and it’s easier to change the business object’s behavior by giving the object a different ISendMessage implementation. As a special extra double bonus, the object using ISendMessage is much easier to test. List&amp;lt;T&amp;gt; is a detail. IList&amp;lt;T&amp;gt; is a concept. &lt;/p&gt;
&lt;p&gt;If you doubt the power of interface programming, then just look at COM. Really. In COM you could only program to an object’s interface, and this allowed objects from different runtimes (Visual Basic versus C), different threading models (objects with a thread affinity versus multi-threaded objects), and different processes (local versus remote) to all work together, plus a host of other features. Interface definitions are the ultimate abstraction (for a statically typed environment!). &lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12891" width="1" height="1"&gt;</description></item><item><title>From LINQ to XPath and Back Again</title><link>http://odetocode.com/Blogs/scott/archive/2009/06/05/12881.aspx</link><pubDate>Fri, 05 Jun 2009 07:52:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12881</guid><dc:creator>scott</dc:creator><slash:comments>12</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12881.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12881</wfw:commentRss><description>&lt;p&gt;Let’s say you wanted to select the parts for a Lenovo X60 laptop from the following XML. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Root&lt;/span&gt;&lt;span style="color: blue;"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Manufacturer &lt;/span&gt;&lt;span style="color: red;"&gt;Name&lt;/span&gt;&lt;span style="color: blue;"&gt;=&lt;/span&gt;"&lt;span style="color: blue;"&gt;Lenovo=&lt;/span&gt;"&lt;span style="color: blue;"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Model &lt;/span&gt;&lt;span style="color: red;"&gt;Name&lt;/span&gt;&lt;span style="color: blue;"&gt;=&lt;/span&gt;"&lt;span style="color: blue;"&gt;X60=&lt;/span&gt;" &lt;span style="color: blue;"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Parts&lt;/span&gt;&lt;span style="color: blue;"&gt;&amp;gt;
        &amp;lt;!-- &lt;/span&gt;&lt;span style="color: green;"&gt;... &lt;/span&gt;&lt;span style="color: blue;"&gt;--&amp;gt;
      &amp;lt;/&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Parts&lt;/span&gt;&lt;span style="color: blue;"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Model&lt;/span&gt;&lt;span style="color: blue;"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Model &lt;/span&gt;&lt;span style="color: red;"&gt;Name&lt;/span&gt;&lt;span style="color: blue;"&gt;=&lt;/span&gt;"&lt;span style="color: blue;"&gt;X200=&lt;/span&gt;"&lt;span style="color: blue;"&gt;&amp;gt;
      &amp;lt;!-- &lt;/span&gt;&lt;span style="color: green;"&gt;... &lt;/span&gt;&lt;span style="color: blue;"&gt;--&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Model&lt;/span&gt;&lt;span style="color: blue;"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Manufacturer&lt;/span&gt;&lt;span style="color: blue;"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Manufacturer &lt;/span&gt;&lt;span style="color: red;"&gt;Name&lt;/span&gt;&lt;span style="color: blue;"&gt;=&lt;/span&gt;"&lt;span style="color: blue;"&gt;...=&lt;/span&gt;" &lt;span style="color: blue;"&gt;/&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Manufacturer &lt;/span&gt;&lt;span style="color: red;"&gt;Name&lt;/span&gt;&lt;span style="color: blue;"&gt;=&lt;/span&gt;"&lt;span style="color: blue;"&gt;...=&lt;/span&gt;" &lt;span style="color: blue;"&gt;/&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Manufacturer &lt;/span&gt;&lt;span style="color: red;"&gt;Name&lt;/span&gt;&lt;span style="color: blue;"&gt;=&lt;/span&gt;"&lt;span style="color: blue;"&gt;...=&lt;/span&gt;" &lt;span style="color: blue;"&gt;/&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Manufacturer &lt;/span&gt;&lt;span style="color: red;"&gt;Name&lt;/span&gt;&lt;span style="color: blue;"&gt;=&lt;/span&gt;"&lt;span style="color: blue;"&gt;...=&lt;/span&gt;" &lt;span style="color: blue;"&gt;/&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;Root&lt;/span&gt;&lt;span style="color: blue;"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;If you know LINQ to XML, you might load up an XDocument and start the party with a brute force approach:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;parts = xml.Root
               .Elements(&lt;span style="color: rgb(163, 21, 21);"&gt;"Manufacturer"&lt;/span&gt;)
                   .Where(e =&amp;gt; e.Attribute(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;).Value == &lt;span style="color: rgb(163, 21, 21);"&gt;"Lenovo"&lt;/span&gt;)
               .Elements(&lt;span style="color: rgb(163, 21, 21);"&gt;"Model"&lt;/span&gt;)
                   .Where(e =&amp;gt; e.Attribute(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;).Value == &lt;span style="color: rgb(163, 21, 21);"&gt;"X60"&lt;/span&gt;)
               .Single()
               .Element(&lt;span style="color: rgb(163, 21, 21);"&gt;"Parts"&lt;/span&gt;);
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;But, the code is ugly and makes you long for the days when XPath ruled the planet. Fortunately, you can combine XPath with LINQ to XML. The System.Xml.XPath namespace includes some XPath specific extension methods, like XPathSelectElement:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;string &lt;/span&gt;xpath = &lt;span style="color: rgb(163, 21, 21);"&gt;"Manufacturer[@Name='Lenovo']/Model[@Name='X60']/Parts"&lt;/span&gt;;
&lt;span style="color: blue;"&gt;var &lt;/span&gt;parts = xml.Root.XPathSelectElement(xpath);
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Now the query is a bit more readable (at least to some), but let’s see what we can do with extension methods. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;static class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ComputerManufacturerXmlExtensions
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;public static &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;XElement &lt;/span&gt;Manufacturer(&lt;span style="color: blue;"&gt;this &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;XElement &lt;/span&gt;element, &lt;span style="color: blue;"&gt;string &lt;/span&gt;name)
    {
        &lt;span style="color: blue;"&gt;return &lt;/span&gt;element.Elements(&lt;span style="color: rgb(163, 21, 21);"&gt;"Manufacturer"&lt;/span&gt;)
                      .Where(e =&amp;gt; e.Attribute(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;).Value == name)
                      .Single();
    }

    &lt;span style="color: blue;"&gt;public static &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;XElement &lt;/span&gt;Model(&lt;span style="color: blue;"&gt;this &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;XElement &lt;/span&gt;element, &lt;span style="color: blue;"&gt;string &lt;/span&gt;name)
    {
        &lt;span style="color: blue;"&gt;return &lt;/span&gt;element.Elements(&lt;span style="color: rgb(163, 21, 21);"&gt;"Model"&lt;/span&gt;)
                      .Where(e =&amp;gt; e.Attribute(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;).Value == name)
                      .Single();
    }

    &lt;span style="color: blue;"&gt;public static &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;XElement &lt;/span&gt;Parts(&lt;span style="color: blue;"&gt;this &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;XElement &lt;/span&gt;element)
    {
        &lt;span style="color: blue;"&gt;return &lt;/span&gt;element.Element(&lt;span style="color: rgb(163, 21, 21);"&gt;"Parts"&lt;/span&gt;);
    }
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Now, the query is short and succinct:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;parts = xml.Root.Manufacturer(&lt;span style="color: rgb(163, 21, 21);"&gt;"Lenovo"&lt;/span&gt;).Model(&lt;span style="color: rgb(163, 21, 21);"&gt;"X60"&lt;/span&gt;).Parts();&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Combine an XSD file with T4 code generation and you’ll have all the extension methods you’ll ever need for pretty XML queries... &lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12881" width="1" height="1"&gt;</description></item><item><title>Catching Up On Lean</title><link>http://odetocode.com/Blogs/scott/archive/2009/06/03/12843.aspx</link><pubDate>Thu, 04 Jun 2009 06:59:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12843</guid><dc:creator>scott</dc:creator><slash:comments>0</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12843.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12843</wfw:commentRss><description>&lt;p&gt;I now have a number of &lt;a href="http://www.poppendieck.com/" target="_blank"&gt;lean software development&lt;/a&gt; books queued up. It started when I saw this single bullet point in a presentation:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Overproduction == Extra Features&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;I’m enjoying the thinking behind lean, and I believe the techniques and vocabulary of lean makes software development more tangible to the folks we work with who don’t write code – and that’s important. &lt;/p&gt; &lt;p&gt;Overproduction in software development happens when you produce a feature that customers rarely use. This is one of lean’s &lt;a href="http://www.leaninnovations.ca/seven_types.html" target="_blank"&gt;seven deadly types of wastes&lt;/a&gt;. The perfect technique to manage this waste is to never create a feature without first establishing a clear value for the feature, but perfection isn’t easy. In commercial software development you’ll inevitably ship some useless bits as you discover the market and the functionality your future customers will value. &lt;/p&gt; &lt;p&gt;Even when you do ship successful bits, the outside world can reprioritize your software. The U.S. healthcare industry, for example, is ultra-sensitive to laws and regulations. A new piece of legislation can change last year’s “must have” feature into this year’s “&lt;a href="http://www.urbandictionary.com/define.php?term=meh" target="_blank"&gt;meh&lt;/a&gt;”. &lt;/p&gt; &lt;h3&gt;Breaking Up Is Hard To Do&lt;/h3&gt; &lt;p&gt;The relationship between overproduction stuck out to me because I’ve wrestled with overproduction for many years on several different products. Software vendors are reluctant to remove features, no matter how rarely used the features may be. Sales people in particular object to cutting anything they think might possibly have the slightest potential to attract a single future sale. &lt;/p&gt; &lt;p&gt;The basic problem is thinking of a software feature as an investment -something to protect moving forward. As Mark Lindell will tell you, &lt;a href="http://codeliability.blogspot.com/" target="_blank"&gt;code is not an investment but a liability&lt;/a&gt;. In lean thinking, features are inventory, and anyone who has come within spitting distance of a business school knows inventory can make cuts in the margin. &lt;/p&gt; &lt;p&gt;Removing a working feature is never an easy decision, but the sooner a vendor sees obsolete features as a cost and waste, the sooner the vendor can jettison the unused inventory that adds no value to the customer or the company. &lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12843" width="1" height="1"&gt;</description></item><item><title>Don't Ask Me If It's Possible</title><link>http://odetocode.com/Blogs/scott/archive/2009/06/02/12820.aspx</link><pubDate>Wed, 03 Jun 2009 04:11:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12820</guid><dc:creator>scott</dc:creator><slash:comments>6</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12820.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12820</wfw:commentRss><description>&lt;p&gt;Years ago, ex-Googler Doug Edwards &lt;a href="http://xooglers.blogspot.com/2005/11/word.html" target="_blank"&gt;wrote a blog post&lt;/a&gt; to explain the meaning behind a few favorite words in the software developer’s vocabulary: orthogonal, cruft, canonical, and the big one - non-trivial. &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;strong&gt;Non-trivial&lt;/strong&gt;&lt;br&gt;It means impossible. Since no engineer is going to admit something is impossible, they use this word instead.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;I’ve spent the bulk of my career developing commercial software, and it’s amazing how many sales people, executives, and marketing managers ask if something is &lt;em&gt;possible&lt;/em&gt;. Example:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Is it possible to reverse the flow of time when we click this button?&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The requests are more realistic, of course, but the stock reply is: &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Given enough resources, anything is possible.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The response doesn’t say the feature is impossible, or even non-trivial. You might think the response is the habitual reply of yet another &lt;a href="http://www.youtube.com/watch?v=a1RxKedYy0s" target="_blank"&gt;passive-aggressive&lt;/a&gt; software developer (the canonical developer, to use Mr. Edward’s lexicon), but I much prefer to think of the reply as a zen-like answer that points the questioner to the realities of software development. Despite what the pointy haired boss hears from tool vendors and analysts, creating software still requires resources – both time and mental effort. &lt;/p&gt; &lt;h3&gt;What I’ve Learned&lt;/h3&gt; &lt;p&gt;Building commercial software for a vertical market is a … non-trivial endeavor. But, not non-trivial in the impossible sense. The problem is you don’t know precisely what features will provide enough value to attract new customers until you’ve done some work. &lt;/p&gt; &lt;p&gt;I’ve generally found that if someone inside an ISV is asking if a feature is &lt;em&gt;possible&lt;/em&gt;, it’s only a feature they want if it comes for free. They haven't done the homework to understand how the feature would work to provide value for the mainstream customer, and the idea is still in an incubation phase. It will be difficult to even estimate the amount of work required. &lt;/p&gt; &lt;p&gt;When they turn the question into: &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;What does it take to get this into our software?&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Then you know they are serious and passionate about the idea, and it’s time to start talking.&amp;nbsp; &lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12820" width="1" height="1"&gt;</description></item><item><title>Iterating on an ASP.NET MVC Model Binder</title><link>http://odetocode.com/Blogs/scott/archive/2009/05/05/12801.aspx</link><pubDate>Wed, 06 May 2009 01:49:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12801</guid><dc:creator>scott</dc:creator><slash:comments>12</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12801.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12801</wfw:commentRss><description>&lt;p&gt;After my last post on &lt;a href="http://odetocode.com/Blogs/scott/archive/2009/04/27/12788.aspx" target="_blank"&gt;model binding tips&lt;/a&gt; I’ve had a number of questions about the nuances of model binding. Let’s work through a sample. &lt;/p&gt; &lt;p&gt;Imagine you have a Recipe class that can hold all the information you need to make &lt;a href="http://allrecipes.com/Recipe/Love-Mussels/Detail.aspx" target="_blank"&gt;Love Mussels&lt;/a&gt;, and now you've decided to build a model binder to bind and validate recipes.&amp;nbsp; &lt;/p&gt; &lt;h3&gt;Iteration 1&lt;/h3&gt; &lt;p&gt;Let’s start with the naive approach. This code has a number of problems. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;RecipeModelBinder &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;IModelBinder
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;public object &lt;/span&gt;BindModel(&lt;span style="color: rgb(43, 145, 175);"&gt;ControllerContext &lt;/span&gt;controllerContext, &lt;span style="color: rgb(43, 145, 175);"&gt;ModelBindingContext &lt;/span&gt;bindingContext)
    {
        &lt;span style="color: blue;"&gt;var &lt;/span&gt;form = controllerContext.HttpContext.Request.Form;

        &lt;span style="color: blue;"&gt;var &lt;/span&gt;recipe = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe&lt;/span&gt;();            
        recipe.Name = form[&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;];
        &lt;span style="color: green;"&gt;// ... and so on for all properties

        &lt;/span&gt;&lt;span style="color: blue;"&gt;if &lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;String&lt;/span&gt;.IsNullOrEmpty(recipe.Name))
        {
            bindingContext.ModelState.AddModelError(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;"..."&lt;/span&gt;);
        }

        &lt;span style="color: blue;"&gt;return &lt;/span&gt;recipe;
    }
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The code works directly off the HttpContext.Request.Form.&lt;/p&gt;
&lt;p&gt;There are a couple difficulties working with the Form collection directly. One problem is how your tests will require more setup to create an HttpContext, Request, and Form objects. &lt;br&gt;&lt;/p&gt;&lt;p&gt;The second problem is related to culture. Values you need from the Form collection are culture sensitive because the user will type a date and time value into their browser using a local convention. However, the URL is another place you might need to check when binding values (the query string and routing data in general), and these values are culture invariant. &lt;/p&gt;
&lt;p&gt;Instead of worrying about all these details, it’s better to use the ValueProvider given to us by the incoming binding context. The value provider is easy to populate in a unit test, and takes care of culture sensitive conversions. &lt;/p&gt;
&lt;h3&gt;Iteration 2&lt;/h3&gt;
&lt;p&gt;We’ll add a GetValue method to help fetch values from the ValueProvider. At runtime the MVC framework populates the provider with values it finds in the request’s form, route, and query string collections. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;RecipeModelBinder &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;IModelBinder
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;public object &lt;/span&gt;BindModel(&lt;span style="color: rgb(43, 145, 175);"&gt;ControllerContext &lt;/span&gt;controllerContext, &lt;span style="color: rgb(43, 145, 175);"&gt;ModelBindingContext &lt;/span&gt;bindingContext)
    {
        &lt;span style="color: blue;"&gt;var &lt;/span&gt;recipe = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe&lt;/span&gt;();
        recipe.Name = GetValue&amp;lt;&lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt;(bindingContext, &lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;);
        &lt;span style="color: green;"&gt;// ... and so on for all properties

        &lt;/span&gt;&lt;span style="color: blue;"&gt;if &lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;String&lt;/span&gt;.IsNullOrEmpty(recipe.Name))
        {
            bindingContext.ModelState.AddModelError(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;"..."&lt;/span&gt;);
        }

        &lt;span style="color: blue;"&gt;return &lt;/span&gt;recipe;
    }

    &lt;span style="color: blue;"&gt;private &lt;/span&gt;T GetValue&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;ModelBindingContext &lt;/span&gt;bindingContext, &lt;span style="color: blue;"&gt;string &lt;/span&gt;key) 
    {
        &lt;span style="color: rgb(43, 145, 175);"&gt;ValueProviderResult &lt;/span&gt;valueResult;
        bindingContext.ValueProvider.TryGetValue(key, &lt;span style="color: blue;"&gt;out &lt;/span&gt;valueResult);            
        &lt;span style="color: blue;"&gt;return &lt;/span&gt;(T)valueResult.ConvertTo(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(T));
    }  
}
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Problem:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you use any HTML Helpers (like Html.TextBox), you’ll see null reference exceptions when validation errors are present. &lt;/p&gt;
&lt;p&gt;One of the side-effects of model binding is that binding the model should put model values into ModelState. When an HTML helper sees there is a ModelState error for “Name”, it assumes it will also find the “attempted value” that the user entered. The helper uses attempted values to repopulate inputs and allow the user to fix any errors. &lt;/p&gt;
&lt;h3&gt;Iteration 3&lt;/h3&gt;
&lt;p&gt;The only change is to set the model value inside GetValue. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;private &lt;/span&gt;T GetValue&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;ModelBindingContext &lt;/span&gt;bindingContext, &lt;span style="color: blue;"&gt;string &lt;/span&gt;key)
{
    &lt;span style="color: rgb(43, 145, 175);"&gt;ValueProviderResult &lt;/span&gt;valueResult;
    bindingContext.ValueProvider.TryGetValue(key, &lt;span style="color: blue;"&gt;out &lt;/span&gt;valueResult);
&lt;strong&gt;    bindingContext.ModelState.SetModelValue(key, valueResult);&lt;/strong&gt;       
    &lt;span style="color: blue;"&gt;return &lt;/span&gt;(T)valueResult.ConvertTo(&lt;span style="color: blue;"&gt;typeof&lt;/span&gt;(T));
}  
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&lt;strong&gt;Problem:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The model binder we’ve written so far will work with controller actions like the following:&lt;/p&gt;&lt;pre class="code"&gt;[&lt;span style="color: rgb(43, 145, 175);"&gt;AcceptVerbs&lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;HttpVerbs&lt;/span&gt;.Post)]
&lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ActionResult &lt;/span&gt;Create(&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe &lt;/span&gt;newRecipe)
{
    &lt;span style="color: green;"&gt;// ...
    &lt;/span&gt;&lt;span style="color: blue;"&gt;return &lt;/span&gt;View(newRecipe);
}
&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;But it won’t work in this scenario:&lt;/p&gt;&lt;pre class="code"&gt;[&lt;span style="color: rgb(43, 145, 175);"&gt;AcceptVerbs&lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;HttpVerbs&lt;/span&gt;.Post)]
&lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ActionResult &lt;/span&gt;Create(&lt;span style="color: rgb(43, 145, 175);"&gt;FormCollection &lt;/span&gt;formCollection)
{
    &lt;span style="color: blue;"&gt;var &lt;/span&gt;recipe = &lt;span style="color: rgb(43, 145, 175);"&gt;RecipeFactory&lt;/span&gt;.Create();
    TryUpdateModel(recipe);
    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(ModelState.IsValid)
    {
        &lt;span style="color: green;"&gt;// save it ...
    &lt;/span&gt;}
    &lt;span style="color: blue;"&gt;return &lt;/span&gt;View(recipe);
}&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;The recipe in the controller action will never see any changes when calling TryUpdateModel, because the model binder is creating and binding data into its own recipe object. Perhaps you never use UpdateModel or TryUpdateModel, but if you expect your model binder to work in any possible situation, you need to make sure the model binder works when someone else creates the model. &lt;/p&gt;
&lt;h3&gt;Iteration 4&lt;/h3&gt;
&lt;p&gt;The only change is to check bindingContext.Model to see if we already have a model. Only when this property is null will we go to the trouble of creating a new model.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public object &lt;/span&gt;BindModel(&lt;span style="color: rgb(43, 145, 175);"&gt;ControllerContext &lt;/span&gt;controllerContext, &lt;span style="color: rgb(43, 145, 175);"&gt;ModelBindingContext &lt;/span&gt;bindingContext)
{
    &lt;span style="color: blue;"&gt;var &lt;/span&gt;form = controllerContext.HttpContext.Request.Form;

&lt;strong&gt;    &lt;span style="color: blue;"&gt;var &lt;/span&gt;recipe = (&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe&lt;/span&gt;)(bindingContext.Model ?? &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe&lt;/span&gt;());
&lt;/strong&gt;    recipe.Name = GetValue&amp;lt;&lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt;(bindingContext, &lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;);
    
    &lt;span style="color: green;"&gt;// ... 

    &lt;/span&gt;&lt;span style="color: blue;"&gt;return &lt;/span&gt;recipe;
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;&lt;strong&gt;Problem:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Congratulations! We just re-implemented the behavior of the DefaultModelBinder - only our model binder is stupid and only works with Recipes. &lt;/p&gt;
&lt;p&gt;If all we need is validation for a specific type of model, we can derive from the built-in binder and override OnModelUpdated or OnPropertyValidating and provide our custom logic. &lt;/p&gt;
&lt;h3&gt;Iteration 5&lt;/h3&gt;
&lt;p&gt;OnModelUpdated is easy to work with, so what follows is the entire listing for our custom model binder. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;RecipeModelBinder &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;DefaultModelBinder 
&lt;/span&gt;{
    &lt;span style="color: blue;"&gt;protected override void &lt;/span&gt;OnModelUpdated(&lt;span style="color: rgb(43, 145, 175);"&gt;ControllerContext &lt;/span&gt;controllerContext,
                                           &lt;span style="color: rgb(43, 145, 175);"&gt;ModelBindingContext &lt;/span&gt;bindingContext)
    {
        &lt;span style="color: blue;"&gt;var &lt;/span&gt;recipe = bindingContext.Model &lt;span style="color: blue;"&gt;as &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe&lt;/span&gt;;
        &lt;span style="color: blue;"&gt;if &lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;String&lt;/span&gt;.IsNullOrEmpty(recipe.Name))
        {
            bindingContext.ModelState.AddModelError(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;"..."&lt;/span&gt;);
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;It turns out we didn’t need any code from those first four iterations, but I hope you find them useful because they demonstrate some common problems I’m seeing in custom model binders. Of course we could take this example even further and eliminate the magic strings, but we’ll leave the work for another day. &lt;/p&gt;
&lt;p&gt;In software development – every iteration is a learning opportunity!&lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12801" width="1" height="1"&gt;</description></item><item><title>6 Tips for ASP.NET MVC Model Binding</title><link>http://odetocode.com/Blogs/scott/archive/2009/04/27/12788.aspx</link><pubDate>Mon, 27 Apr 2009 07:12:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12788</guid><dc:creator>scott</dc:creator><slash:comments>14</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12788.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12788</wfw:commentRss><description>&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd410405.aspx" target="_blank"&gt;Model binding&lt;/a&gt; in the ASP.NET MVC framework is simple. Your action methods need data, and the incoming HTTP request carries the data you need. The catch is that the data is embedded into POST-ed form values, and possibly the URL itself. Enter the DefaultModelBinder, which can magically convert form values and route data into objects. Model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment. &lt;/p&gt; &lt;p align="center"&gt;&amp;nbsp;&lt;img title="magic default model binder" alt="magic default model binder" src="http://www.odetocode.com/aimages/200904/magicmodelbinder_3.jpg" width="477" border="0" height="287"&gt;&amp;nbsp; &lt;/p&gt; &lt;p&gt;Here are some tips on how to take advantage of model binding in your MVC projects.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Tip #1: Prefer Binding Over Request.Form&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;If you are writing your actions like this ..&lt;/p&gt;&lt;pre class="code"&gt;[&lt;span style="color: rgb(43, 145, 175);"&gt;AcceptVerbs&lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;HttpVerbs&lt;/span&gt;.Post)]
&lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ActionResult &lt;/span&gt;Create()
{
    &lt;span style="color: rgb(43, 145, 175);"&gt;Recipe &lt;/span&gt;recipe = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe&lt;/span&gt;();
    recipe.Name = Request.Form[&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;];
    
    &lt;span style="color: green;"&gt;// ...
    
    &lt;/span&gt;&lt;span style="color: blue;"&gt;return &lt;/span&gt;View();
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;.. then you are doing it all wrong. The model binder can save you from using the Request and HttpContext properties – those properties make the action harder to read and harder to test. One step up would be to use a FormCollection parameter instead:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ActionResult &lt;/span&gt;Create(&lt;span style="color: rgb(43, 145, 175);"&gt;FormCollection &lt;/span&gt;values)
{
&lt;span style="color: rgb(43, 145, 175);"&gt;    Recipe &lt;/span&gt;recipe = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe&lt;/span&gt;();
    recipe.Name = values[&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;];      
            
    &lt;span style="color: green;"&gt;// ...
            
    &lt;/span&gt;&lt;span style="color: blue;"&gt;return &lt;/span&gt;View();
}
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;With the FormCollection you don’t have to dig into the Request object, and sometimes you need this low level of control. But, if all of your data is in Request.Form, route data, or the URL query string, then you can let model binding work its magic:&lt;/p&gt;&lt;pre class="code"&gt;[&lt;span style="color: rgb(43, 145, 175);"&gt;AcceptVerbs&lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;HttpVerbs&lt;/span&gt;.Post)]
&lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ActionResult &lt;/span&gt;Create(&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe &lt;/span&gt;newRecipe)
{            
    &lt;span style="color: green;"&gt;// ...
    
    &lt;/span&gt;&lt;span style="color: blue;"&gt;return &lt;/span&gt;View();
}&lt;/pre&gt;
&lt;p&gt;In this example, the model binder will create your newRecipe object and populate it with data it finds in the request (by matching up data with the recipe’s property names). It’s pure auto-magic. There are many ways to &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.bindattribute_members.aspx" target="_blank"&gt;customize&lt;/a&gt; the binding process with “white lists”, “black lists”, prefixes, and marker interfaces. For more control over when the binding takes place you can use the&amp;nbsp; UpdateModel and TryUpdateModel methods. Just beware of unintentional binding – see Justin Etheredge’s &lt;a href="http://www.codethinked.com/post/2009/01/08/ASPNET-MVC-Think-Before-You-Bind.aspx" target="_blank"&gt;Think Before You Bind&lt;/a&gt;. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tip #2: Custom model binders&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Model binding is also one of the extensibility points in the MVC framework. If you can’t use the default binding behavior you can provide your own model binders, and mix and match binders. To implement a custom model binder you need to implement the IModelBinder interface. There is only method involved - how hard can it be?&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public interface &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;IModelBinder
&lt;/span&gt;{
&lt;span style="color: blue;"&gt;    object &lt;/span&gt;BindModel(&lt;span style="color: rgb(43, 145, 175);"&gt;ControllerContext &lt;/span&gt;controllerContext, &lt;br&gt;                     &lt;span style="color: rgb(43, 145, 175);"&gt;ModelBindingContext &lt;/span&gt;bindingContext);
}&lt;/pre&gt;
&lt;p&gt;Once you get neck deep into model binding, however, you’ll discover that the simple IModelBinder interface doesn’t fully describe all the implicit contracts and side-effects inside the framework.&amp;nbsp; If you take a step back and look at the bigger picture you’ll see that model binding is but one move in a carefully orchestrated dance between the model binder, the ModelState, and the HtmlHelpers. You can pick up on some of these implicit behaviors by &lt;a href="http://aspnet.codeplex.com/SourceControl/changeset/view/23011#338676" target="_blank"&gt;reading the unit tests&lt;/a&gt; for the default model binder. &lt;/p&gt;
&lt;p&gt;Scott Hanselman demonstrates a non-trivial model binder in his post “&lt;a href="http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx" target="_blank"&gt;Splitting DateTime – Unit Testing ASP.NET MVC Custom Model Binders&lt;/a&gt;”. One detail I want to call out about Scott’s DateTime splitter is how you still don’t need to use Request.Form when building the model. Inside the GetA&amp;lt;T&amp;gt; method you’ll see how Scott uses the binding context’s ValueProvider property to fetch data. The ValueProvider represents an amalgamation of all data from the request’s posted form values, routing data, and query string. Scott’s example is great, but it is missing one detail – the propagation of binding errors. &lt;/p&gt;
&lt;p&gt;If the default model binder has problems putting data into your object, it will place the error messages and the erroneous data value into ModelState. You can check ModelState.IsValid to see if binding problems are present, and use &lt;a href="http://msdn.microsoft.com/en-us/library/dd410404.aspx" target="_blank"&gt;ModelState.AddModelError&lt;/a&gt; to inject your own error messages. See &lt;a href="http://www.asp.net/Learn/mvc/tutorial-36-cs.aspx" target="_blank"&gt;this very simple tutorial&lt;/a&gt; for more information on how ModelState and HtmlHelpers can work together to present validation errors to the user.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;If you scroll down the comments to Scott’s post you’ll see &lt;a href="http://www.free-h.org/" target="_blank"&gt;Sebastien Crocquesel’s&lt;/a&gt; patch for Scott’s code. If a conversion fails, Sebastien’s code will use ModelState.AddModelError to propagate the error. Both the controller action and the view can look in ModelState to see if there was a binding problem. The controller would need to check ModelState for errors before saving stuff into the database, while the view can check ModelState for errors to give the user validation feedback. One important note is that the HtmlHelpers you use in a view will require ModelState to hold both a value (via ModelState.SetModelValue) and the error (via AddModelError) or you’ll have runtime errors (null reference exceptions). The following code can demonstrate the problem:&lt;/p&gt;&lt;pre class="code"&gt;[&lt;span style="color: rgb(43, 145, 175);"&gt;AcceptVerbs&lt;/span&gt;(&lt;span style="color: rgb(43, 145, 175);"&gt;HttpVerbs&lt;/span&gt;.Post)]
&lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ActionResult &lt;/span&gt;Create(&lt;span style="color: rgb(43, 145, 175);"&gt;FormCollection &lt;/span&gt;Form)
{
    &lt;span style="color: green;"&gt;// this is the wrong approach ...
    &lt;/span&gt;&lt;span style="color: blue;"&gt;if &lt;/span&gt;(Form[&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;].Trim().Length == 0)
        &lt;span style="color: rgb(43, 145, 175);"&gt;ModelState&lt;/span&gt;.AddModelError(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;, &lt;span style="color: rgb(163, 21, 21);"&gt;"Name is required"&lt;/span&gt;);

    &lt;span style="color: blue;"&gt;return &lt;/span&gt;View();
}
&lt;/pre&gt;
&lt;p&gt;The above code creates a model error without ever setting a model value. It has other problems, too, but it will create exceptions if you render the following view. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="background: rgb(255, 238, 98) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue;"&gt;= &lt;/span&gt;Html.TextBox(&lt;span style="color: rgb(163, 21, 21);"&gt;"Name"&lt;/span&gt;, Model.Name) &lt;span style="background: rgb(255, 238, 98) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Even though you’ve specified Model.Name as the value for the textbox, the textbox helper will see the model error and attempt to display the “attempted value” that the user tried to put in the model. If you didn’t set the model value in model state you’ll see a null reference exception. 
&lt;p&gt;&lt;strong&gt;Tip #3: Custom Model Binding via Inheritance&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you’ve decided to implement a custom model binder, you might be able to cut down on the amount of work required by inheriting from DefaultModelBinder and adding some custom logic. In fact, this should be your default plan until you are certain you can’t subclass the default binder to achieve the functionality you need. For example, suppose you just want to have some control over the creation of your model object. The DefaultModelBinder will create object’s using Activator.CreateInstance and the model’s default constructor. If you don’t have a default constructor for your model, you can subclass the DefaultModelBinder and override the CreateModel method. &lt;/p&gt;
&lt;p&gt;Jimmy Bogard has an example of sub classing the DefaultModelBinder in his post titled “&lt;a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/03/17/a-better-model-binder.aspx" target="_blank"&gt;A Better Model Binder&lt;/a&gt;”. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tip #4: Using Data Annotations for Validation&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Brad Wilson explains everything beautifully in this post: &lt;a href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html" target="_blank"&gt;DataAnnotations and ASP.NET MVC&lt;/a&gt;. &lt;/p&gt;
&lt;p&gt;I encourage you to go read Brad’s post, but if you are in a hurry, here is a summary:&lt;/p&gt;
&lt;p&gt;.NET 3.5 SP1 shipped a System.ComponentModel.DataAnnotations assembly that looks to play a central role as we move forward with the .NET framework. By using data annotations and the &lt;a href="http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471" target="_blank"&gt;DataAnnotationsModelBinder&lt;/a&gt;, you can take care of most of your server-side validation by simply decorating your model with attributes. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Recipe
&lt;/span&gt;{
    [&lt;span style="color: rgb(43, 145, 175);"&gt;Required&lt;/span&gt;(ErrorMessage=&lt;span style="color: rgb(163, 21, 21);"&gt;"We need a name for this dish."&lt;/span&gt;)]
    [&lt;span style="color: rgb(43, 145, 175);"&gt;RegularExpression&lt;/span&gt;(&lt;span style="color: rgb(163, 21, 21);"&gt;"^Bacon"&lt;/span&gt;)] 
    &lt;span style="color: blue;"&gt;public string &lt;/span&gt;Name { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }

    &lt;span style="color: green;"&gt;// ...
&lt;/span&gt;}
&lt;/pre&gt;
&lt;p&gt;The DataAnnotationsModelBinder is also a great sample to read and understand how to effectively subclass the default model binder. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tip #5 : Recognize Binding and Validation As Two Phases&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Binding is about taking data from the environment and shoving it into the model, while validation is checking the model to make sure it meets our expectations. These are different different operations, but model binding tends to blur the distinction. If you want to perform validation and binding together in a model binder, you can – it’s exactly what the DataAnnotationsModelBinder will do. You can also find samples like &lt;a href="http://blog.stormid.com/archive/2009/04/07/automatic-model-validation-with-asp.net-mvc-xval-castle-and-a.aspx" target="_blank"&gt;Automatic Model Validation with ASP.NET MVC, xVal, Castle, and a Custom Binder&lt;/a&gt; (John McDowall), and &lt;a href="http://geekswithblogs.net/michelotti/archive/2009/03/16/enterprise-library-validation-application-block-with-mvc-binders.aspx" target="_blank"&gt;Enterprise Library Validation Application Block with MVC Binders&lt;/a&gt; (Steve Michelotti).&amp;nbsp; However, one thing that is often overlooked is how the DefaultModelBinder itself separates the binding and validation phases. If all you need is simple property validation, then all you need to do is override the OnPropertyValidating method of the DefaultModelBinder. &lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tip #6: Binders Are About The Environment&lt;/strong&gt;
&lt;/p&gt;&lt;p&gt;Earlier I said that “model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment”. Generally, when we think of binder we think of moving data from the routing data and posted form values into the model. However, there is no restriction of where you find data for your model. The context of a web request is rich with information about the client. A good example is another Scott Hanselman post on automatically binding the user’s identity into a model see: &lt;a href="http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx"&gt;IPrincipal (User) ModelBinder in ASP.NET MVC for easier testing&lt;/a&gt;. 
&lt;/p&gt;&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;
&lt;/p&gt;&lt;p&gt;Model binding is beautiful magic, so take advantage of the built-in magic when you can. I think the topic of model binding could use it’s own dedicated web site. It would be a very boring web site with lots of boring code, but model binding has many subtleties. For instance, we never even got to the topic of culture in this post. 
&lt;/p&gt;&lt;p&gt;Do you have any model binding tips?&lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12788" width="1" height="1"&gt;</description></item><item><title>Life and Times of an ASP.NET MVC Controller</title><link>http://odetocode.com/Blogs/scott/archive/2009/04/22/12785.aspx</link><pubDate>Thu, 23 Apr 2009 05:44:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12785</guid><dc:creator>scott</dc:creator><slash:comments>1</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12785.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12785</wfw:commentRss><description>&lt;p&gt;The May issue of MSDN Magazine is now on-line with my article “&lt;a href="http://msdn.microsoft.com/en-us/magazine/dd695917.aspx" target="_blank"&gt;The Life and Times of an ASP.NET MVC Controller&lt;/a&gt;”. &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;In this article, I will dissect the ASP.NET MVC framework and look at how controllers work. I'll explain how the framework interacts with your controllers and how you can influence those interactions. I'll look at controller factories, controller actions, action filters, and action results as well.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;I don’t like &lt;a href="http://www.pragprog.com/the-pragmatic-programmer/extracts/coincidence" target="_blank"&gt;programming by coincidence&lt;/a&gt;, and I hope this article gives you everything you need to work confidently with MVC controllers. In addition to the technical details, I also believe you have to properly apply a technology to make great software – thus the next installment of Extreme ASP.NET in July will cover some guiding principles to keep in mind when developing applications with the ASP.NET MVC framework. &lt;/p&gt; &lt;p&gt;Looking even further down the road (September seems so far away), I’m not sure what I’ll dig into next. Will it be web forms? More ASP.NET MVC? If there is something you want to hear about that is related to the ASP.NET server-side runtime - drop me a line or leave a comment. &lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12785" width="1" height="1"&gt;</description></item><item><title>ASP.NET MVC Controls and Good versus Evil</title><link>http://odetocode.com/Blogs/scott/archive/2009/04/09/12756.aspx</link><pubDate>Thu, 09 Apr 2009 07:53:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12756</guid><dc:creator>scott</dc:creator><slash:comments>19</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12756.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12756</wfw:commentRss><description>&lt;p&gt;&lt;a href="http://www.flickr.com/photos/zoomar/145322737/" target="_blank"&gt;&lt;img title="Good Unicorn versus Evil Unicorn" alt="Good Unicorn versus Evil Unicorn" src="http://www.odetocode.com/aimages/200904/goodversusevil_4.jpg" width="304" align="right" border="0" height="229"&gt;&lt;/a&gt;Luis and David recently posted about the controls that appear in the &lt;a href="http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471" target="_blank"&gt;ASP.NET MVC Futures 1.0&lt;/a&gt; release. &lt;/p&gt; &lt;ul&gt; &lt;li&gt;Luis Abreu: &lt;a href="http://msmvps.com/blogs/luisabreu/archive/2009/03/16/the-mvc-framework-the-repeater-control.aspx" target="_blank"&gt;The MVC framework: the Repeater control&lt;/a&gt;&lt;/li&gt; &lt;li&gt;David Hayden: &lt;a href="http://davidhayden.com/blog/dave/archive/2009/04/07/ASPNETMVCControlsASPNETMVCFuturesRepeaterControlExample.aspx"&gt;ASP.NET MVC Controls in ASP.NET MVC Futures - Repeater Control Example&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;I’ve seen some discussions where people positively erupt at any mention of the word “control” in an MVC setting. These are the people who consider ASP.NET Web Forms as the ultimate source of evil in the universe – a cross between a Sith lord and a velociraptor. The idea of introducing controls, with un-testable event handling code and giant gobs of view state, is a travesty that will corrupt the minds of all developers before devouring their children. They must be stopped.&amp;nbsp;&amp;nbsp; &lt;/p&gt; &lt;h3&gt;The Case For Controls&lt;/h3&gt; &lt;p&gt; Let’s take the simple scenario of rendering a text input in the browser. If you are using the ASP.NET MVC framework release with no additional libraries, you’ll be looking to use one of the 4 Html helper TextBox methods (excerpted for space below):&lt;br&gt;&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;string &lt;/span&gt;TextBox(&lt;span style="color: blue;"&gt;&lt;/span&gt;... &lt;span style="color: blue;"&gt;string &lt;/span&gt;name);
&lt;span style="color: blue;"&gt;string &lt;/span&gt;TextBox(&lt;span style="color: blue;"&gt;&lt;/span&gt;... &lt;span style="color: blue;"&gt;string &lt;/span&gt;name, &lt;span style="color: blue;"&gt;object &lt;/span&gt;value);
&lt;span style="color: blue;"&gt;string &lt;/span&gt;TextBox(&lt;span style="color: blue;"&gt;&lt;/span&gt;... &lt;span style="color: blue;"&gt;string &lt;/span&gt;name, &lt;span style="color: blue;"&gt;object &lt;/span&gt;value, IDictionary&amp;lt;&lt;span style="color: blue;"&gt;string&lt;/span&gt;, &lt;span style="color: blue;"&gt;object&lt;/span&gt;&amp;gt; htmlAttributes);
&lt;span style="color: blue;"&gt;string &lt;/span&gt;TextBox(&lt;span style="color: blue;"&gt;&lt;/span&gt;... &lt;span style="color: blue;"&gt;string &lt;/span&gt;name, &lt;span style="color: blue;"&gt;object &lt;/span&gt;value, &lt;span style="color: blue;"&gt;object &lt;/span&gt;htmlAttributes);
&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;A text input is a pretty trivial control, but even these 4 options don’t give you a clean path to the entire universe of things you might want to do when displaying a value in a text input, like specifying a formatting string to use when converting the model value to a string. One solution is to write additional helper methods, or include an additional library with the methods already written, but you are only adding to the number of method overloads a developer has to parse when they just want to display a simple text input. In the end, you’ll still be looking at code similar to the following…&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="background: rgb(255, 238, 98) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue;"&gt;= &lt;/span&gt;Html.TextBox(&lt;span style="color: rgb(163, 21, 21);"&gt;"ReleaseDate"&lt;/span&gt;,
                 &lt;span style="color: rgb(43, 145, 175);"&gt;String&lt;/span&gt;.Format(&lt;span style="color: rgb(163, 21, 21);"&gt;"{0:d}"&lt;/span&gt;, Model.ReleaseDate),
                 &lt;span style="color: blue;"&gt;new &lt;/span&gt;{ @class = &lt;span style="color: rgb(163, 21, 21);"&gt;"special" &lt;/span&gt;})&lt;span style="background: rgb(255, 238, 98) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;"&gt;%&amp;gt;
&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;…versus the declarative syntax of the MVC futures TextBox control…&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;mvc&lt;/span&gt;&lt;span style="color: blue;"&gt;:&lt;/span&gt;&lt;span style="color: rgb(163, 21, 21);"&gt;TextBox &lt;/span&gt;&lt;span style="color: red;"&gt;Name&lt;/span&gt;&lt;span style="color: blue;"&gt;="ReleaseDate" &lt;/span&gt;&lt;span style="color: red;"&gt;Format&lt;/span&gt;&lt;span style="color: blue;"&gt;="{0:d}"
             &lt;/span&gt;&lt;span style="color: red;"&gt;class&lt;/span&gt;&lt;span style="color: blue;"&gt;="special" &lt;/span&gt;&lt;span style="color: red;"&gt;runat&lt;/span&gt;&lt;span style="color: blue;"&gt;="server" /&amp;gt;
&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Note that the MVC control does &lt;em&gt;not&lt;/em&gt; inject view state into the rendered output, but that’s not to say that the MVC controls don’t have some issues. One issue is that they still inherit properties, behaviors, and events from System.Web.UI.Control, and some of those inherited features don’t make sense in an MVC view. &lt;/p&gt;
&lt;p&gt;I think I'm still happier using Html helpers. &lt;/p&gt;
&lt;p&gt;Here are some advantages I see to using controls:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The declarative model is easier to scan because the named properties are explicit, whereas with HtmlHelpers the order of the unnamed parameters is important. &lt;/li&gt;
&lt;li&gt;It’s easier to add extensibility via additional properties instead of adding yet another extension method overload.&lt;/li&gt;
&lt;li&gt;The logic for a custom control is encapsulated in a class, with all of the benefits of using a class, whereas the entry point for an HtmlHelper is just a method.&lt;/li&gt;
&lt;li&gt;Controls would probably be the preferred way to work for designers (of the human variety). &lt;/li&gt;
&lt;li&gt;Controls would probably open up more opportunities for vendors to ship functionality. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;And the disadvantages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;They remove the benefit of strongly typing the model, which is a huge loss. &lt;/li&gt;
&lt;li&gt;Someone under the influence of the dark side can wire up event handlers. &lt;/li&gt;
&lt;li&gt;It’s possible to build controls that are too smart for their own good (or for the view’s good).&lt;/li&gt;
&lt;li&gt;Nobody knows what HTML might appear when the control renders (which, to be fair, is also true of 3rd party Html helpers). &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;It’s also worth pointing out that there are other solutions, besides controls, to the often clumsy Html helpers. By sticking to view-specific models, conventions, and effective CSS with JavaScript, you can remove many of the concerns that the HtmlHelpers burden themselves with. Using a view engine other than the web forms view engine can also solve some of these issues. &lt;/p&gt;
&lt;p&gt;&lt;b&gt;What do you think? &lt;/b&gt;&lt;/p&gt;
&lt;p&gt;Will MVC controls be the spawn of Satan, or the blessing of a saint? &lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12756" width="1" height="1"&gt;</description></item><item><title>MVC Course is Coming Online!</title><link>http://odetocode.com/Blogs/scott/archive/2009/04/07/12750.aspx</link><pubDate>Tue, 07 Apr 2009 18:10:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12750</guid><dc:creator>scott</dc:creator><slash:comments>0</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12750.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12750</wfw:commentRss><description>&lt;a href="http://www.pluralsight.com/main/olt/courses.aspx"&gt;&lt;img src="http://www.pluralsight.com/main/images/psod/PSODAd_Large1.png" align="right"&gt;&lt;/a&gt;
&lt;p&gt;Just a quick note to let you know that the first three modules of my &lt;a href="http://www.pluralsight.com/main/olt/Course.aspx?n=aspdotnet-mvc" target="_blank"&gt;ASP.NET MVC course&lt;/a&gt; are ready for consumption at &lt;a href="http://www.pluralsight.com/main/olt/Courses.aspx" target="_blank"&gt;Pluralsight! On-Demand&lt;/a&gt;. Pluralsight is building a fantastic library of online content you can view as a subscriber, or see in person via &lt;a href="http://www.pluralsight.com/main/ilt/Courses.aspx" target="_blank"&gt;instructor led training&lt;/a&gt; at a classroom or on-site at your place. &lt;br&gt;&lt;/p&gt;&lt;p&gt;There is also a heap of &lt;a href="http://www.pluralsight.com/main/screencasts/default.aspx" target="_blank"&gt;free screencasts&lt;/a&gt; and &lt;a href="http://www.pluralsight.com/main/olt/samples.aspx" target="_blank"&gt;previews&lt;/a&gt; to wet your appetite. &lt;/p&gt; &lt;p&gt;A single subscription can get you access to training for WPF, C#, .NET, ASP.NET, AJAX, WF, WCF, Silverlight, BizTalk, with more on the way. &lt;/p&gt; &lt;p&gt;P.S. I’ve heard the &lt;a href="http://www.pluralsight.com/main/olt/Course.aspx?n=linq-fundamentals" target="_blank"&gt;LINQ class&lt;/a&gt; is awesome, too…&lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12750" width="1" height="1"&gt;</description></item><item><title>Putting the M in MVC – Part III</title><link>http://odetocode.com/Blogs/scott/archive/2009/04/05/12740.aspx</link><pubDate>Mon, 06 Apr 2009 06:22:00 GMT</pubDate><guid isPermaLink="false">2a1db9d5-42e2-4e6d-a60a-04dde226509f:12740</guid><dc:creator>scott</dc:creator><slash:comments>8</slash:comments><comments>http://odetocode.com/Blogs/scott/comments/12740.aspx</comments><wfw:commentRss>http://odetocode.com/Blogs/scott/commentrss.aspx?PostID=12740</wfw:commentRss><description>&lt;p&gt;In the last post we talked about using &lt;a href="http://odetocode.com/Blogs/scott/archive/2009/04/01/12736.aspx" target="_blank"&gt;entities as the models&lt;/a&gt; in an MVC application. This approach works well until an application reaches a certain level of complexity, at which point entities as the M in MVC can become painful. &lt;/p&gt; &lt;p&gt;I believe entities exist to serve the business layer. They also have a role in the data access layer, but only because the data access layer has to be acutely aware of entities. The reverse is not true – entities don’t need to know details about the data access layer nor how they are saved in persistent storage. Entities aren’t owned by the UI, or the data access layer. Entities are business objects and are owned by the business layer. &lt;/p&gt; &lt;p&gt;An application that supports a complex business needs a fine-tuned layer of business logic. You know an application is growing in complexity when you uncover scenarios like these:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Validation rules go beyond mere database constraints - &lt;em&gt;maximum discount is 10% unless an administrator is overriding the discount percentage&lt;/em&gt;.&amp;nbsp; &lt;/li&gt;&lt;li&gt;Multiple sets of validation policies are in effect - &lt;em&gt;contracts signed in the state of Maryland after Jan 1, 2009 require additional checks to meet regional law #443570&lt;/em&gt;.  &lt;/li&gt;&lt;li&gt;Entities are involved in long running business processes - &lt;em&gt;the request for proposal requires approval from three directors before moving to a published state&lt;/em&gt;.  &lt;/li&gt;&lt;li&gt;The application integrates with external applications and services - &lt;em&gt;changes to any customer information must be published to the CRM system within 10 minutes&lt;/em&gt;. &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;These types of requirements have a significant impact on the design and behavior of the business layer and its entities. You want all this complicated business stuff in a layer where it is testable, maintainable, and free from the influence of all the infrastructure that surrounds it – databases, data grids, message queues, communication protocols, and the technology du jour. It’s a business layer built with business objects that encapsulate business state and business behavior. It’s the secret sauce that makes money for your company. It’s a rich model of your domain. &lt;/p&gt; &lt;p&gt;So - why wouldn’t we want to use this rich domain model inside of our views? Isn’t it every young view’s dream to grow up and marry an extraordinarily rich, fat model?&lt;/p&gt; &lt;h3&gt;Models, Models Everywhere&lt;/h3&gt; &lt;p&gt;Views can grow complex just as quickly as business logic can grow complex. Complex views might exhibit some of the following conditions.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Displays aggregate information from across the application (reporting views).  &lt;/li&gt;&lt;li&gt;Displays information from disparate sources (composite views).  &lt;/li&gt;&lt;li&gt;Lives on a different tier (the view is built using JavaScript, JSON, and client-side data binding). &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Perhaps you don’t consider these views as super-complex because you build them all the time, but the types of views we are talking about in the above three bullet points do place requirements and constraints on the model. For example, the UI may require a model that can serialize into a JSON or RSS format. &lt;/p&gt; &lt;p&gt;If you share your entities or domain model with the UI layer, you’ll find your business objects have to serve two masters. The requirements from these two masters will pull your business objects in different directions, and they won’t be optimized to fit in either role. &lt;/p&gt; &lt;p&gt;&lt;img src="http://www.odetocode.com/aimages/200904/mismatch_6.jpg"&gt;&lt;/p&gt; &lt;p&gt;Also, ask yourself these questions about the model for your views:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Who determines what properties the model should have?  &lt;/li&gt;&lt;li&gt;Who invokes business logic on the the model?  &lt;/li&gt;&lt;li&gt;Who owns the model?&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;Answers:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;The view.  &lt;/li&gt;&lt;li&gt;Not the view.  &lt;/li&gt;&lt;li&gt;The view. &lt;/li&gt;&lt;/ol&gt; &lt;p&gt;Complex applications often require multiple models. There is the domain model that encapsulates your company’s secret money-making business sauce, and then there are multiple view models that the UI layer consumes. Somewhere in between is logic that maps data between the various models. This isn’t a new idea, and it was at one time known as the &lt;a href="http://c2.com/cgi/wiki?ModelModelViewController" target="_blank"&gt;Model Model View Controller&lt;/a&gt; pattern.&lt;/p&gt; &lt;p&gt;You might create a model class for each type of view, like a – MovieReviewViewModel, and perhaps all the UI models derive from a base class. The model classes will hold just the state that their respective views require. These classes don’t need behavior – they are essentially just data transfer objects. In a sense, the model classes also become contracts that explicitly describe what the controller needs to put together for the UI, and the view author sees a model with just the information they need. &lt;/p&gt; &lt;p&gt;Of course, building these additional models comes with a price. &lt;/p&gt; &lt;ul&gt; &lt;li&gt;You have to map data from the domain model into view model classes, and vice versa.  &lt;/li&gt;&lt;li&gt;You have to figure out how to provide validation logic for view models.  &lt;/li&gt;&lt;li&gt;You’ll write more code, and manage more classes. &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;It’s up to you to decide if the benefits are worth the price:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Your entities and business objects are optimized for business logic  &lt;/li&gt;&lt;li&gt;Your view models are optimized for the UI  &lt;/li&gt;&lt;li&gt;You achieve separation and isolation of the business and UI concerns&amp;nbsp; &lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;&lt;/h3&gt; &lt;h3&gt;What Was The Original Question?&lt;/h3&gt; &lt;p&gt;It was:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;“I have created domain entities like Customer, Order, etc. They come out of&amp;nbsp; repository classes backed by NHibernate. I’m wondering if I send them directly to the view or if I create a ViewModel class to hold data. I’m confused by all the terminology”.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;I haven’t given a definitive answer, but I hope I’ve given you enough of my opinion to see that the answer depends on the complexity of your application and its long term goals. For forms-over-data applications, passing your entities can be a simple and effective solution. For more complex applications you may need models built specifically for your views to maintain the integrity and maintainability of your business objects. &lt;/p&gt;&lt;img src="http://odetocode.com/Blogs/aggbug.aspx?PostID=12740" width="1" height="1"&gt;</description></item></channel></rss>