blogs.conchango.com

welcome to the conchango blogging site
Welcome to blogs.conchango.com Sign in | Join | Help
in Search

Anthony Steele's Blog

  • Architecture with layers, active records, and onions

    In the 1990s I coded on a few systems where the architecture was that we attached database functionality to our business objects, so you could do something like

     

      someObject.Value = 4;

      someObject.Save();

     

    While this looks appealing, this pattern (I later learned that it is called active record) has fallen out of favour, in favour of a model where the database code is contained not in each object, but in a layer that deals with database and nothing else, e.g:

     

    someObject.Value = 4;

    dataLayer.Save(someObject);

     

    Now the data layer depends upon the object model, and not vice versa. Database code is grouped together, and is easier to change or replace. These days it's often services as well as databases that data comes from and goes to.

     

    We have the "layered" application as the default mainstream pattern. However there have been new ideas percolating. Inversion of control gives us tools to manage and rearange these layers.

     

    I read Jeffrey Palermo's Onion Architecture and found myself nodding in agreement. I don't really mind how much it resembles Hexagonal, it's good either way.

     

    This is a workable, flexible  model, where the object model is made from Plain Old Objects with no special attributes, interfaces or base classes, and knows nothing about any persistence, service or UI layers.

     

    I have also been watching  Rob Conery's ASP.net MVC storefront demo video series. It's excellent. Despite supposedly being about the asp.net MVC kit, it shows a lot of good things about a LINQ to SQL data layer, IOC, mocking and testability. And the pattern is much like the onion.

     

    But the problem with LINQ to SQL in the default configuration is that the object model is not central, it is in the LINQ data layer.


    There are two ways around this,

     

    First, make LINQ to SQL worth differently, to instead make LINQ to SQL use the object model rather than its own objects. Ian Cooper shows how to do this in his series.

     

    Secondly, you can use the objects generated by LINQ to SQL as data transfer objects only, and copies data from them into the object model. Rob Connery takes this approach and it is surprisingly painless.

     

    In part 10, Rob Connery does something surprising to me - he makes the Shopping cart object aware of the repository interface, so that it can save dependant data. It is given a repository interface on creation, in a Dependency Injection pattern.

     

    This is interesting, this object is using the active record pattern? And if so, is it a bad thing? The coupling that made this a bad idea originally is not present.

     

    To my mind this arangment is not ideal. It may be better to push this code out one layer and attach it to the domain object with extension methods. Extension methods in general give an interesting new possibility - that the object itself is just a data container, but with the right extensions in play it knows how to save itself, or display itself, or whatever the current layer requires.

  • Linq to SQL: testing, the long way around

    Linq to SQL is great. You can open up your Db schema, drag some tables in, and in no time you have a data context class with loads of functionality, and data classes for all of the entities. No more recordsets to unpack into objects, no more fields to pack into SQL params, just lists of strongly typed ojects. Even better, the classes are partial so that you can extend them.

    It seems natural to extend the data context by adding methods like
    var orders= MyDataContext.GetOrdersForCustomer(myCustomer.Id);

    Methods like these are trivial to implement with Linq:

    from o in orders where o.CustomerId = customerId select o;

    And Linq makes persistence simple too. 

    Now the problem comes in when you think about layering and mocking. You'd like to have a interface e.g. "IDataStore", with an implementation of it that is backed by the database, and another mock implementation for testing. You'd like to have the data classes to be defined where they depend on neither of these implementations, but both implementations can reference them.

    But Linq to SQL's code isn't laid out like this if you drag and drop. The DataContext doesn't implement any interfaces. The data classes are defined in the same namespace as the DataContext. You can test the data classes by just creating and populating them, but you can't test anything that depends on data retrieval without using the datacontext and behind it, the database.

    It's taken me a while to get there, but this seems to be the problem that Ian Cooper is solving in Architecting LINQ To SQL Applications, part 5

    Hence the"long way around" to seeing why Ian was on about that. Linq to SQL can be used in other ways besides drag and drop, and some of these ways will give you what you want.

  • A method should have only one return statement. Discuss.

    I heard again recently that "A method should have only one return statement" and of "The single-return law", that more than one return was a poor coding practice. I disagree.

     

    public int IsThisCodeSoBad(int param)
    {
       if (param == 0)
         return 0;

       foreach(foo in bar)
       {
          If foo.fish()
          {
            return 1;
          }
       }

       return 2;
    }
     

     

    I have never seen any evidence for the belief that that multiple exit points pose a coding risk, or are bad style. I do not know of any formal study that has found this to be the case, on C# code or on code in any other language.

     

    Coding horror recently talked about "Spartan programming", and mentioned "frugal use of control structures, with early return whenever possible."

     

    One of the few links on the topic that I could find was "Return statements and the single exit fantasy":

    http://www.leepoint.net/JavaBasics/methods/method-commentary/methcom-30-multiple-return.html

     

    Take a look at some of the comments on the Daily WTF (http://thedailywtf.com/Articles/Refactoring_to_the_Max.aspx ) where this issue is raised, particularly this one:

     

    Re: Refactoring to the Max

    2006-04-05 02:25 • by John Hensley

               

    The main reason for the single return "law" in C is to make sure you clean up memory, locks, handles, etc. before you leave a function. 

    This, on the other hand, is Java code.

     

    Apparently the reason for this "law" was that when coding in C or the like, it was natural to deallocate resources near the end of the function. Thus any extra exit points were an invitation to memory leaks. There are two reasons why this is no longer the case:

    Firstly, garbage collected languages make explicit deallocation unnecessary in most cases.

    Secondly, try...finally blocks and using statements allow deallocation to happen with greater certainly at the end of any block of code when it is needed.


    In any event, a function with multiple exit points is a far lesser issue than a goto. In some cases it is the simplest way to code now that we have control structures to deal with it.  But beware of returns in the middle of loops or highly nested code. All other things being equal, avoid them, since they are less readable and predictable.

    It is absolutely fine to use it as a first check on the parameters after entering a function, before getting down to the serious work and allocating those resources,– it's more readable than embedding the rest of the function in an if-block. However throwing an exception is the more usual case for this.

     

    My view of the matter is:

     

    • There are cases where a single return is more readable, and cases where it isn't. See if it reduces the number of lines of code, makes the logic clearer or makes the control structures less deeply nested.
    • More than one return style may be a bad habit in C code, but there is no evidence for it being bad in more modern languages.
    • There is no law requiring only one exit point for a method. Some people have an unsubstantiated belief in the superiority of this style.
    • Requiring fewer return statements for purposes of centralising resource deallocation is not a common need in modern languages that have garbage collection and try..finally blocks.

    Therefore, use as many returns as suits your artistic sensibilities, because it is a layout and readability issue, not a technical one.

     

    There's another issue at play here, about rules being adhered to without people grasping the reason why they are adhering to them, and thus keeping the rule in force after the need for it has evaporated. Rules should be given along with reasons for them.

     

    Addendum:

    Watching the DailyWTF commentators (who have a fairly high opinion of their own coding skills, given that they are essentially gathered there to point and laugh) try and repeatedly fail to translate the following code into a single expression underscores that the multiple-exit points version can be in some cases easier to understand, read, and modify:

    if (condition1(x))
      return true;
    if (condition2(x))
      return false;
    if (condition3(x))
      return true;
    return false;


    You'd think that this is the same as

    return condition1(x) || !condition2(x) || condition3(x);,

    However the one-liner version returns true if all conditions are false, unlike the original. Furthermore, it evaluates condition3 if condition2 is true, which the original does not.

     

    You could also code it as:

     

               bool result = false;

    if (condition1(x))
      result = true;
    if (condition2(x))
      result = false;
    if (condition3(x))
      result = true;

     

    return result;

     

    However this also evaluates condition3 if condition2 is true, which the original does not. I'm sure that the original logic can be replicated with only one return, but it's not going to be as elegant.

     

  • Resharper and Source Analysis, not playing together

    I've had Microsoft Source Analysis (AKA StyleCop) installed for a couple of weeks. Yesterday I have very belatedly taken the plunge into Resharper.

     

    I have gotten used to the style promoted by Source Analysis. I've gotten into the zone of feeling that warm fuzzy glow from code having no warnings. Howard van Rooijen calls this something akin to OCD and he may be right.

     

    As an aside, if you're coding in C#, I feel that you should get used to the coding style that this tool promotes. It's the most authoritative standard layout that there is, and will most likely be widely used. It's the style that has the backing of Microsoft, and has tools for checking adherence. Other styles don't have those advantages.

     

    All I've done with it so far with Resharper is similar OCD-type things, clicking on what it flags up and deciding to suppress or fix the message for a similar warm-fuzzy feeling when the code is clean again.

     

    There were reasons why I didn't install Resharper sooner - resharper 4.0 has just recently come out of beta, and now we have licences on request. So far, Resharper has been excellent and you should try it at your convenience.

     

    Unfortunately, the two tools don't play well together on all machines, and my laptop is affected. When I edit project properties I now get an obscure error: "COM object that has been separated from its underlying RCW cannot be used."

     

    This error is mentioned here  and here.

     

    I now have to say goodbye to one of these tools until this situation is resolved. From this laptop, Source Analysis has gone on holiday. Hopefully it will come back soon, feeling refreshed and ready to help me out. Resharper and I are waiting.

  • User interface usablity with spoken numbers

    Just a quick note on something that was on my mind.

    I knew someone who lived on a "Seven Sisters road", at number 20. She knew that "Seven Sisters" was a really bad name for a road. Just picture yourself phoning for a taxi at "Number 20, Seven Sisters road". Say it three times quickly if you're not hearing the issue.

    Also "One" was a bad name for a train company - Imagine anouncements like "The 12:20 One service to Basingstoke is on time on platform three" People who arrive on platform 3 at 12:20:15 are going to be sorely disapointed.

    Is there a moral for techies in this? Maybe. But it is a user interface design issue in the broader sense, and shows how user interfaces can mislead people, impair thier performance and cause frustration in ways that the original designer did not anticipate. Often "getting it right" just means not falling into any of a large number of potential pitfalls. Some of which are not obvious.

  • REST from WCF 3.5

    WFC is well known to be brilliant at SOAP, and fans of WCF may be aware that in version 3.5 may be aware of the cool new features. But the rest of us (the REST of us, haha, I'm so funny)  may not know that it addresses in a simple and flexible way other scenarios- that is, serving XML or JSON data off simple Urls in a REST style.

     

    This note is be based information from talks by Aaron Skonnard (http://www.pluralsight.com/blogs/aaron/) and Richard Blewett (http://www.dotnetconsult.co.uk/weblog2/) given at Devweek. I went to these talks to get a basic understanding of WCF, and found a couple of interesting features as well.

     

    Before the REST in introduced , I'll start with a simple service that when you give it your name, will greet you.

     

    The contract is:

     

    using System.ServiceModel;

     

    namespace GreeterLib

    {

        [ServiceContract]

        public interface IGreeterService

        {

            [OperationContract]

            string Greet(string name);

        }

    }

     

    The service implementation is

     

    namespace GreeterLib

    { 

        public class GreeterService : IGreeterService

        {

            public string Greet(string name)

            {

                return string.Format("Hello, {0}", name);

            }

        }

    }

     

    This is hosted for debug purposes in a console as follows:

     

    using System;

    using System.ServiceModel;

     

    using GreeterLib;

     

    namespace GreeterConsole

    {

        class Program

        {

            static void Main(string[] args)

            {

                using (ServiceHost serviceHost = new ServiceHost(typeof(GreeterService)))

                {

                    serviceHost.Open();

     

                    Console.WriteLine("WCF Service is running...");

                    Console.ReadLine();

     

                    serviceHost.Close();

                }

     

                Console.WriteLine("WCF Service has closed");

            }

        }

    }

     

    And as always with WFC, the config file does a lot of the heavy lifting of tying things together:

      

    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>

      <system.serviceModel>

        <bindings>

         

        </bindings>

        <services>

          <service name ="GreeterLib.GreeterService" behaviorConfiguration="Default">

            <host>

              <baseAddresses>

                <add baseAddress="http://localhost:8080/greeter"/>

              </baseAddresses>

            </host>

            <endpoint

              address=""

              binding ="basicHttpBinding"

              contract="GreeterLib.IGreeterService" />

          </service>

        </services>

        <behaviors>

          <serviceBehaviors>

            <behavior name="Default">

              <serviceMetadata httpGetEnabled="true"/>

            </behavior>

          </serviceBehaviors>

        </behaviors>

      </system.serviceModel>

    </configuration>

     

     

    So far so usual and SOAPy. I can run the console, and verify that at http://localhost:8080/greeter there is a service, it has wsdl at http://localhost:8080/greeter?wsdl, which specifies the soap that I would need to craft if I wanted to talk to it. I'm not going to do that manually.

     

    To do this in a REST style, we change as follows:

    The contract needs a WebGet attribute, specifying the URL to match:

     

    using System.ServiceModel;

    using System.ServiceModel.Web;

     

    namespace GreeterLib

    {

        [ServiceContract]

        public interface IGreeterService

        {

            [OperationContract]

            [WebGet(UriTemplate = "greet/{name}")]

            string Greet(string name);

        }

    }

     

     

    The program needs to use WebServiceHost:

     

    using System;

    using System.ServiceModel;

    using System.ServiceModel.Web;

     

    using GreeterLib;

     

    namespace GreeterConsole

    {

        class Program

        {

            static void Main(string[] args)

            {

                using (WebServiceHost serviceHost = new WebServiceHost(typeof(GreeterService)))

                {

                    serviceHost.Open();

     

                    Console.WriteLine("WCF Service is running...");

                    Console.ReadLine();

     

                    serviceHost.Close();

                }

     

                Console.WriteLine("WCF Service has closed");

            }

        }

    }

     

    The config needs to use the webHttpBinding binding

     

          <service name ="GreeterLib.GreeterService" behaviorConfiguration="Default">

            <host>

              <baseAddresses>

                <add baseAddress="http://localhost:8080/greeter"/>

              </baseAddresses>

            </host>

            <endpoint

              address=""

              binding ="webHttpBinding"

              contract="GreeterLib.IGreeterService" />

          </service>

     

    And there you go. You can now run this, and hit the URL http://localhost:8080/greeter/greet/Anthony

     

    and get the response

    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello, anthony</string>

     

    You can also return data in JSON format by setting attributes.

     

    But if you hack around a bit, you can also take full control of the XML returned, and serve some Plain Old XML if you want, as follows:

     

    The contract must return a Message:

     

    using System.Runtime.Serialization;

    using System.ServiceModel;

    using System.ServiceModel.Channels;

    using System.ServiceModel.Web;

     

    namespace GreeterLib

    {

        [ServiceContract]

        public interface IGreeterService

        {

            [OperationContract]

            [WebGet(UriTemplate = "greet/{name}")]

            Message Greet(string name);

        }

    }

     

    The service:

     

    using System.ServiceModel.Channels;

    using System.Xml;

    using System.Text;

    using System.IO;

     

    namespace GreeterLib

    {

     

        public class GreeterService : IGreeterService

        {

            public Message Greet(string name)

            {

                XmlReader xmlReader = MakeXml(name);

                return Message.CreateMessage(MessageVersion.None, "", xmlReader);

            }

     

            private XmlReader MakeXml(string name)

            {

                StringBuilder buffer = new StringBuilder();

                using (XmlWriter xmlWriter = XmlWriter.Create(buffer))

                {

                    xmlWriter.WriteStartDocument();

                    xmlWriter.WriteStartElement("greeting");

                    xmlWriter.WriteAttributeString("type", "hello");

                    xmlWriter.WriteString(string.Format("Hello, {0}", name));

                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndDocument();

                }

     

                TextReader reader = new StringReader(buffer.ToString());

                return XmlReader.Create(reader);

            }

        }

    }

     

    And you'll ret the returned data:

     

    <greeting type="hello">Hello, anthony</greeting>

     

    So there it is: POX over REST served by WCF. And it wasn't very difficult.

  • LINQ as a DSL

    What kind of thing is Language Integrated Query, exactly? You can draw the line in a number of places, but I am going to cut it down to the core, where LINQ is a Domain Specific Language.

     

    There are LINQ-enabling language features, i.e the language extensions of type inference:

                var s = "This is a string";

     

    Anonymous types and instance initialiser blocks:

                var anObject = new { x = 3, y = 4.5, z = true };

     

    Lambdas:

                var someStrings = new List<string>();

                var longStrings = someStrings.Where(item => item.Length > 5);

     

    Also extension methods, and the c# code in System.Linq.

     

    So, once all of this is factored out, what is left of LINQ? It is just a compiler rule (or rules) for turning

                var longStringsLinq =

                    from sItem in longStrings

                    where sItem.Length > 5

                    select sItem;

     into

                var longStringsLinq = someStrings.Where(item => item.Length > 5).Select(sItem => sItem);

     

    Whereafter compilation carries on as before. The transformation rule is a Domain-Specific Language which is baked into the c# Version 3 compiler.

     

    We have the option of using the other enabling features for our own purposes. But the LINQ DSL is not accessible, unlike in some languages such as Ruby, in which DSLs are user accessible. I still prefer reading c# code to Ruby code, but I'm thinking - what would c# look like if we could define our own DSLs in a relatively easy way? What would you do with it? Would chaos or enlightenment result?

     

    (this post was inspired by Neal Ford's talk at devweek on "“Design patterns” in dynamic languages")

  • Devweek - first two days

    Monday was a wet and windy day. It was a day of all-day workshops, and I elected to get  all the WPF done at once. Dave Wheeler gave an excellent presentation.

    Interesting  that desktop is far more entrenched than Silverlight, for a couple of reasons: firstly it has been out and stable for longer, and secondly that it has an niche (advanced or scalable desktop Windows user interfaces) for which there is no competitor, whereas Silverlight's is competing with flash and a lot of flavours of AJAX.

    I came out with a much better overview of WCF. And more desire to use it.

    Tuesday

    Tuesday was a sunny day, and the conference had moved to the bottom levels of the Barbican. And grown much larger, with far more people, and vendor booths. The barbican is  wonderful, huge labyrinth. This is the first year that the conference is in this larger venue. I got a few pieces of swag.

    Excluding the staff, the gender ratio must have been about 50 male to 1 female.

    David Wheeler gave the keynote speech, on Rich Internet Applications. 

    New tools since last DevWeek:
    VS 2008 AJAX
    Silverlight 1

    On the way now:
    ASP.NET – MVC, Data services
    WPF Enhancements
    Entity framework

    We are looking at Software in the cloud
    Social networking -> social change

    Rich applications are driven by media and conversations.

    And we have to monetise the web -  it has to pay for itself, by search placement and ads.

    What is a RIA?
    - data driven
    - secure
    - good performance
    - Runs connected
    - Engaging

    Trade off Reach vs. richness. 
    HTML has the widest reach, least richness,


    AJAX can be used for RIA with wider reach
    Silverlight for RIA with slightly less reach, more richness

    WinForms for richer, less reach. Not a RIA anymore.
    WPF-> most richness, least reach.

    The compelling thing about Silverlight is not flash developers using Silverlight, it is C# developers using Silverlight. There are a lot more C#