Welcome to EMC Consulting Blogs Sign in | Join | Help

Anthony Steele's Blog

  • 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.

     

     

    Update: Richard Tobin has sent me this comment by email:

    This discussion is a common one that we continually face where I work.  I took your example and reworked it into a single return as follows:
     
    private bool LotsOfReturns(int x)
    {
        if (Condition1(x))
            return true;
        if (Condition2(x))
            return false;
        if (Condition3(x))
            return true;
        return false;
    }
     

    private bool OneReturn(int x)
    {
        bool flag = Condition1(x);

        if (!flag)
        {
            if (!Condition2(x))
            {
                flag = Condition3(x);
            }
        }

        return flag;
    }
     
    After compiling and looking at the IL with Reflector, the single return routine seemed more compact and efficient, and the C# source seems less tricky. 

     

    All I can really say is that he has suceeded in converting the code, and which one "seems less tricky" is going to be a matter of taste.

     

     

     

  • 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# developers. They can use existing skills. Unlike flash, can interact with the dev.

    NBC Olympics will be a big stress test of SilverLight.

    Then I was on on to track 2, in Cinema 3, Floor 4 for 10 ways to improve your code, Neal Ford, Thoughtworks. It was a good session, mostly ideas not code, but not dry. Ask me about the angry moneys some time. I should print out a "YAGNI" sign some time.

    Daniel Moth gave us a tour of VS2008, and Alex Homer gave a session on the Enterprise Application block. It's not the most glamourous code, but it works very well. We use it, maybe should use it more. Version 4 is apparently out soon, and will include a Dependency Injection block.

  • DevWeek (and DeveloperDay)

    Conchango is considerately (though unexpectedly) sending me to DevWeek (http://www.devweek.com/) next week. I'll try to give feedback on the event and on sessions that I attend. Looking at the agenda, the top topics seem to be WPF in desktop and Silverlight flavours, ASP.Net with AJAX, WCF, patterns and testing.

    I've never been to a devweek before, and I'm quite pleased to go. But I have been to several DeveloperDay (http://www.developerday.co.uk/) events, I like them. The information density is high, so maybe by the end of a whole week like that my brain will be reeling. 

    DeveloperDay is a great community event: it’s free for attendees, presenters are not paid, and the topics presented are driven by the developer community with calls for presentation and agenda voting. The venue and facilities (but not the presenters) are provided for free by Microsoft in Reading. But in some ways DeveloperDay is a victim of its own success – the venue has a finite capacity, and the event is fully booked very rapidly, with many of the places going to the same keen people each time.

    Increasing the capacity of DeveloperDay would probably mean rethinking the whole thing –  using a different, larger venue would not be free, so  the attendees would have to pay for it, so the speakers would have to be chosen as drawcards, etc. That sounds more like devweek, and the community feeling of DeveloperDay is fine like it is.  Developer day is instead branching out with regional events like http://www.developerdayscotland.com/ and http://www.dddireland.com/

    Devweek looks interesting, and I'll try to report back; but with five tracks it's probable that I will miss whichever session you really wanted to hear about. I'm already torn between several of them.

  • Duplicate Finder

    A while ago (June last year) I wrote a utility to detect runs of duplicate lines in files, which is useful for looking for repetitive code that should be refactored. Then I stopped work on it, since it was done.  The original blog post is here and the project is up on CodePlex here.

    This year I have revisited it with two new features which I think make it much more usable.

    The first feature  is an MSBuild Task wrapper to compliment the command line interface. This means that instead of using a command line like: 

    DuplicateFinder -r -t8 -eAssemblyInfo *.cs

    You can now also use an equivalent MSBuild Script:

    <Project DefaultTargets="RunTest"
        xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
       
      <UsingTask TaskName="DuplicateFinder"
     AssemblyFile="$(MSBuildExtensionsPath)\DuplicateFinder.Tasks.dll" />
     
      <ItemGroup>
        <TestFiles
       Include="..\..\**\*.cs" 
       Exclude="..\..\**\AssemblyInfo.cs" 
     />
      </ItemGroup>
     
      <Target Name="RunTest">
        <DuplicateFinder Files="@(TestFiles)"
            DuplicateThreshold="8"
      />
      </Target>
    </Project>

    This may be more verbose, but it has the advantage that you can run it as part of your automated build process. In case you don't always look at the build output, you can use the CountThresholdForError and LengthThresholdForError options to the MSBuild task to fail the build if the duplicates in the source are too numerous or too long.

    The second new feature is to cut down or eliminate the false positives. Whole files can already be excluded, but we also need to exclude duplicates where the first line starts with a particular prefix. I'll show you the reason for this.

    If we run the duplicate finder on its own source code (excluding the generated AssemblyInfo.cs files, which we know will all look much the same), we get the following:

    > DupFinder.exe -r -t7 -eAssemblyInfo.cs *.cs
     
    Processing in C:\Temp\DuplicateFinder\DuplicateFinderLib
    6 files read
    Duplicate of length 7 at:
     Line 1-7 in C:\Temp\DuplicateFinder\DuplicateFinderLib\DuplicateEventArgs.cs
     Line 1-7 in C:\Temp\DuplicateFinder\DuplicateFinderLib\LineItem.cs
     Line 1-7 in C:\Temp\DuplicateFinder\DuplicateFinderLib\LineItemList.cs
    1 duplicate found

    The duplicate, line 1-7 of three different files, consists of these lines:

    using System;
    using System.Collections.Generic;
    using System.Text;
     
    namespace DuplicateFinderLib
    {
        /// <summary>

    While these lines may be the same, I don't regard them as "bad" or "cut and paste" code. So I exclude duplicates where the first line starts with "using". Like so:


    DupFinder.exe -r -t7 -eAssemblyInfo.cs -xusing *.cs
    Processing in C:\Temp\DuplicateFinder\DuplicateFinderLib
    6 files read
    0 duplicates found

    You can also do this in the MSBuild file. More than one prefix can be excluded.

  • New Microsoft certifications

    I'm back from Holiday and getting going into the new year. For those of you .Net developers considering Microsoft certification exams, the following may be of interest:

    Exam 70-502 Microsoft .NET Framework 3.5 - Windows Presentation Foundation. Expected to be released in February 2008. http://www.microsoft.com/learning/exams/70-502.mspx

    Exam 70-503 Microsoft .NET Framework 3.5 - Windows Communication Foundation. Expected to be released in February 2008. http://www.microsoft.com/learning/exams/70-503.mspx

    Exam 70-504 Microsoft .NET Framework 3.5 - Windows Workflow Foundation. Expected to be released in March 2008.  http://www.microsoft.com/learning/exams/70-504.mspx

This Blog

Syndication

Powered by Community Server (Personal Edition), by Telligent Systems