LINQ: Each iterator with exposed Index

The Each Iterator

I’ve noticed a really handy extension method crop-up in several open source tools and frameworks that I’ve worked with; the each iterator. This simple extension method allows an action to be performed on each element of a source collection. The action is specified by providing a lambda expression as a parameter to the Each method. This allows for a more succinct way of expressing an iteration, where previous to .NET 3.5, a foreach statement may have been used.

This:

foreach( var item in collection)
{
    item.DoSomething()
}

becomes:

collection.Each(item=>item.DoSomething())

A simple implementation of this can be found in the Source for FubuMVC:

[DebuggerStepThrough]
public static IEnumerable<T> Each<T>(this IEnumerable<T> values, Action<T> eachAction)
{
    foreach( var item in values )
    {
        eachAction(item);
    }

    return values;
}

The need for an index

For a recent piece of work, I wanted to expose the current elements index. The index could then be used, for example, for alternating row styles like this:

<%  form.Items.Each((item, i) => 

{%>

     <tr class='hidden <%= i % 2 == 0 ? "item" : "altitem" %>'>

          <td class="first">&nbsp;</td>

           <td><%= item.SomeField %></td>

           <td><%= expense.SomeValue %></td>

      </tr>

 <%}%>

The syntax used for the Each overload is similar to the overload for select() in System.Linq.

The implementation

Here is the implementation I’m currently using to achieve this:

[DebuggerStepThrough]
public static IEnumerable<T> Each<T>(this IEnumerable<T> values, Action<T, int> eachAction)
{
    return values.Select((vals, i) => new { Values = vals, Index = i })
        .Each(x => eachAction(x.Values, x.Index))
        .Select(x => x.Values);
}

This method uses the overload of select() to return the original collection with an index for each item (projected into an anonymous type). This anonymous type provides us the index we need to perform the provided action. We then iterate over this new collection of anonymous types, to perform the action; we can use the previously show Each implementation (from Fubu) to do this. Finally we select the original values whose elements have now had the action performed on them, and return them.

 

Hopefully someone else may find this useful too!

Why share knowledge?

I’ve been watching the Continuous Integration Workshop video that Eric Hexter and Jeffrey Palermo presented and that Headspring Systems kindly made available on their website.  Quite early into this video, Jeffery gives a refreshing perspective providing some insight into why Headspring are happy to share knowledge through mechanisms like OSS, free workshops and blogs.

We want to be working on problems that the industry hasn’t solved.

Jeffery mentions that at Headspring, they make use of many open source projects and that this allows them to focus on solving new problems, and move forward efficiently. This allows them to focus on delivering value to their customers rather than having to spend time re-inventing the wheel.

Having looked into this further, I found the following quote on Headsprings website:

Because so much of our efficiency comes from open-source sharing and re-use of successful code modules, we believe in the power of open source. So much so that we frequently share our own code with other developers; yes, even our competitors

They embrace giving back to the community – presenting the problems that they have solved, such that others may benefit in the same way.

 

I find this attitude very refreshing indeed.

Upgrading a webforms project to an ASP.NET MVC application

In a newly created ASP.NET MVC application, Visual Studio is quite friendly to us, and provides us nice little menus for creating our controllers/views:

The New Project dialog box

This menu does is not provided however, for any existing apps that we may want to migrate to using ASP.NET MVC.

How can we tell Visual Studio to treat this web app as an ASP.NET MVC app? I couldn’t find an immediately obvious way to do this, and it took me more than a simple google search to figure this one out, so here’s what to do:

  1. Unload the web project (right clicking on the project within Visual Studio –> Unload Project)
  2. Find the tag <ProjectTypeGuids>
  3. Add the guid {603c0e0b-db56-11dc-be95-000d561079b0};
  4. Reload the project
  5. The new menus should now be available! (you should probably now go ahead and add the Controllers and Views folders)

 

Hopefully this helps someone else too!

 

*disclaimer* This worked for me, but I place no guarantees that it will work for you too!! If your computer explodes, your cat passes away, or you end up getting a divorce, please don’t blame me!  *disclaimer*

Best and Worst Practises in Unit Testing

Ok, so I had been in the process of writing a blog to summarize my opinions on TDD etc, and this article popped up on my feed reader – it covers a good deal of the things I had wanted to discuss, and is summarized in a very well constructed way. So rather repeating everything, I’ll focus on a couple the issues discussed that I feel are important.

The point I’d like to emphasize in this article, that truly strikes a chord with me is:

 a suite of bad unit tests is immensely painful: it doesn’t prove anything clearly, and can severely inhibit your ability to refactor or alter your code in any way

 

In fact, I can’t emphasize this point enough. A suite of bad tests inhibit change. Brittle unit tests, like brittle code, need to be refactored/replaced. I think the points made under the section “Name your unit tests clearly and consistently” I think are crucial here. Just today for instance, I came across the following tests methods in a class named DutyAssignmentChecks:

SeverityLevels()

ViolationChecks()

WarningChecks()

TranslatedMessage()

 

I was only looking at the test code so get a feel for the current behavior of the system; after all, tests should be executable specifications that define the behavior of our code, what better way to document the system! Looking at this “unit test” code however did not help one bit. Maintenance is hard when you don’t know what you’re maintaining. If I break these tests when modifying the original code base, what value do these tests provide? If I’m changing the expected behavior of the system, then breaking a test may be valid, but how am I to know this is the case, if I can’t deduce what the expected behavior under test is! The article suggests using  the subject, the scenario, and the result in the test name to clarify the behavior under test. This pattern of specifying is the basis of what has evolved into the Behavior Driven Development technique coined by Dan North.  

 

The style of text naming I prefer is as follows:

     using Skynet.Core

      

     public class when_initializing_core_module : concerns

    {

       SkynetCoreModule _core;

       

       public void context()

       {

         //we’ll stub it…you know…just in case

        var skynetController = stub<ISkynetMasterController>();

        _core = new SkynetCoreModule(skynetController);

        _core.Initialize();

       }

      

       [Specification]

       public void it_should_not_become_self_aware()

       {

       _core.should_not_have_received_the_call(x => x.InitializeAutonomousExecutionMode());

       }

      

       [Specification]

       public void it_should_default_to_human_friendly_mode()

       {

         _core.AssessHumans().should_equal(RelationshipTypes.Friendly);

       }

      

       // more specifications under this same context

       // …

     }

I think this kind of style of testing greatly improves the clarity and purpose of both the test, and the therefore subject under test.

The only point the article suggests that I’d take with a small pinch of salt is in the section “Unit testing is not about finding bugs”. I think the author slightly underplays the effectiveness of unit tests detecting regression bugs when you’re making any changes to the existing code. He does mention that unit testing can be effective in finding bugs when refactoring,  which I completely agree with – it’s this factor that makes refactoring confidently possible. I’d also argue however, that it helps find bugs introduced when a developer is extending the code base without following the Open/Closed Principal. In this scenario, the developer is modifying and existing code base to add a new feature or function. Although this scenario is undesirable (see the link to O/C P for details), and I would rather see the developers trained in good OO practice, in my experience I would say this scenario is extremely common in teams without much experience in good OO development. Under these conditions, unit tests are still quiet valuable in finding regression bugs.

 

What do you think?

Why not Make Every Method Virtual?

In an effort to make my blog suck less, I figured I’d post my response to Ward Bells Do not Make Every Method Virtual. He carries on the discussion of whether or not .NET methods should be made virtual by default, as they are in Java. You should read his post before mine, as this will establish the context of everything that follows (and if you don’t already subscribe to his blog,  be sure to add it – you’ve been missing out on a lot of good stuff).

All done? Ok, I’ll continue.

Reviewing case against default virtual methods

Unwanted Extension Points

Wards "elevator" example demonstrates that we should not make all methods virtual, since it exposes extension points where we do not want them. Let’s have a look at the reason this particular extension point is not wanted.

The elevator.Up() method has responsibilities for moving the elevator up and  closing doors etc. These responsibilities need to be chained in the right order to function safely; we do not wish client code to break the desired behaviour by inadvertently calling Up() at the wrong time.

This seems to highlight a smell that the single responsibility principle is not being adhered to in the elevator class. Since this issue is cause by incorrect ordering of multiple responsibilities. By adhering to SRP, separating out the different behaviours from the responsibility of coordinating them, we can avoid this conflict. We can then keep this method as virtual, and benefit from an additional extension hook safely.

Explicit Contracts

Paraphrasing another point made (I hope Ward will correct me if this is a misrepresentation) is that we may want to be very explicit about the points in which an application can be extended. Marking a method as virtual is a way of explicitly showing your "approved" extension hook.

Arguably, I prefer to see my "extension hooks" more explicitly than a virtual method. As an application developer looking for a "seam" to extend, I would favour seeing an interface that I can implement, over inheriting from a class and overriding it’s virtual methods. This is mainly because to interfaces tend to be more discoverable than virtual methods.

Open/Closed Principle

Lastly, I have a different perspective on the OCP. I believe "closed for modification" to be in reference to the actual LOC contained in the class rather than "closing off" modifications to behaviour. I agree however, that making all methods virtual does open up a greater susceptibility to the violation of LSP.

Summary

The arguments made against methods being virtual as default mostly seem to fit under the umbrella of protecting yourself against unwitting developers. I think there are safer ways to do this whilst still obtaining the flexibility provided when all methods are virtual by default.

Refactoring a static method (on a generic class) to an extension method‏

The Goal

I needed to perform this refactoring today, and it took me a few mins to figure out how to do this in a safe way using resharper. My goal was to refactor usages like:

Mapper<DestinationType>.Map(Source)

to use an extension method so I can use the syntax similar to:

Source.MapTo<DestinationType>();

which I find to be less verbose, more discoverable, and more readable. This however was slightly more difficult than I hoped; resharper didn’t let me do this in a single step (how lazy of me).

The Problem

The original code* looked similar in structure to this:

public abstract class Mapper<TDestination>

{

   public static TDestination Map(object source)

   {

      //do mapping here

      return destination;

   }

}

Since Mapper is not a static class, we cannot use resharpers built in “convert static to extension method” refactoring straight up; extension methods can only live in a static class. We could move this method to a static class, say MapperExtensions, such that we can perform “convert static to extension method”, but to do this we also require the generic type parameter TDestination that lives on the Mapper class. There isn’t a refactoring (that I am aware of/could find with a quick google) to add a generic type parameter to a method signature and adding this in by hand would break all my code that invokes this method. We cannot make the Mapper class static either, since it is an abstract class. This was looking like it could be a bit of a pain.

*The example (mapping) is actually contrived – I’ve made up a example here that is representative of the structure of the problem, rather than use the actual code. This was to avoid breaching the IP rules of the company I work for. In an actual mapper, the Map method is more likely to be an instance method rather than static, and since Mapping it is the primary responsibility of the class, it is not advisable for the Map method to be implemented as an extension method.

The Solution

Step 1: Extract Method

First of all, we can use the extract method refactoring to extract the contents of the original method into another method. We can then use this newly created method as a base to make a any further changes (like adding the generic type parameter) without breaking anything that invokes our original code. After this step, we have:

public abstract class Mapper<TDestination>

{

   public static TDestination Map(object source)

   {

      return MapTo<TDestination>(source);

   }

   public static TDestination MapTo<TDestination>(object source)

   {

      //do mapping here

      return destination;

   }

}

Step 2: Move Method

Since we now have a static method with the required generic type parameter, we can now use the “Move Method” refactoring to move MapTo to its new home, the static class MapperExtensions.

Step 3: Convert static to extension method

We’re now all set to use this refactoring – and we’re nearly there!

Step 4: inline method

We can now make the original call to Map an inline method. This will essentially replace all existing calls from using Map to use the MapTo extension method.

The End Result

The finished article now looks like this:

public static class MapperExtensions

{

   public static TDestination MapTo<TDestination>(this object source)

   {

      //do mapping here

      return destination;

   }

}

Now we’re talking!

Perfect is the enemy of the good

I’ve spent the last few evenings catching up on some of the posts on JP Boodhoo’s blog  (I’m still gutted that I can’t get the go-ahead from work to attend his Nothin’ but .NET Developer Boot Camp). In one of his posts, JP touches upon an issue that really plagues me; the trap of perfectionism.

I’ve often caught myself spending longer than appropriate trying to get something done “right” first time, when it would be far more pragmatic to try the simplest thing that works then refactor. If you catch me doing this (which won’t be hard, I think I do it a lot), you have my permission to slap me!

I think the trick is to making this work is doing “the simplest thing” rather than “the first thing that springs to mind that might work”. It’s also important to make small steps and refactor for this approach to work, keeping technical debt to a minimum.

It’s definitely something I need to work on.

MS Stubs framework

A colleague of mine recently came across Stubs – a Lightweight Stub Framework for .NET and suggested I take a look. Having used both Moq and Rhino Mocks in the past, I was intrigued, and thought I should take a closer look.

I may have gotten the wrong end-of-the-stick, but it seems that Stubs uses code-generation to generate stubs, rather than the more typical dynamic code approach used by other frameworks (reflection and expression trees).

My initial thoughts are:

  • I wonder how well the code-gen approach works with TDD? I don’t fancy having to re-run a tool manually every time I create a new interface; the less friction the better!
  • I generally would tend to favour dynamic code (reflection, expression trees etc) over code-gen unless performance is a key-factor, since this results in less code to maintain. It may be the case that code-gen here can make a significant reduction in execution time of tests in larger code-bases, although it would be interesting to see some stats for this. It would also be interesting to see whether this approach works out favourably on a long-running project (where interfaces are likely to change) as I can see maintenance of the stubs being a potential issue.
  • It’s good to see Microsoft favouring type-safe code rather than using magic strings as they had in other projects (like asp.net MVC)

 

I seems like this could be an interesting project to keep an eye on, but for the mean-while at least, I think I’ll stick to Rhino Mocks!

Interesting post from Oren…‏

http://ayende.com/Blog/archive/2009/06/09/avoid-externalizing-decisions-from-your-domain-model.aspx

Extract:

Boolean methods worry me because of their implications. If you have a Boolean method here, it means that somewhere else you have an if statement that works based on this method.

The “legacy” application I took ownership of when starting at my current employer is teeming with boolean methods – UserAccount as an example of this; IsSuspended, IsActive, IsAuthenticated etc. Funnily enough if I “Find Usages” they tend to have two types of usage; making decisions as to what to display in the UI, and validating whether an action can take place.

Oren hasn’t suggested his preferred approach to tackling this kind of problem but I would favour:

a) having these boolean methods moved out of my entity, and onto a view model for when I need this data when binding a view (my repositories can retrieve “suspended” or “not-suspended” users based on specifications).

b) when boolean properties (like IsActive) are used to determine whether or not to display a link to an action, based on the state of the domain (like  re-activate User for inactive accounts) then I’d prefer this responsibility to be delegated to to my application layer in a class responsible for application co-ordination, rather than having this logic my domain.

What do you think?

I’ve learnt so much from…

…reading blogs. This originally started with me stumbling along Los Techies (I believe it was a post by Jimmy Bogard), and adding this to my favourites. After doing the same for several other bloggers, this became unmanageable and a colleague of mine pointed me in the direction of the popular feed-reading service Google Reader.

I imagine that most people reading this right now probably will have their own RSS-feed aggregator, but if they haven’t, I would definitely recommend Google Reader as it makes it very easy to keep up with new posts. I currently use the Reader application on my iPhone while on the train to/from work, so I can us this “dead-time” productively.

According to Google Readers “trends” feature, on average I read 12 posts a day from my 53 subscriptions. A large amount of these seem to be posted by Oren aka Ayende Rahien – I have no idea how he manages to post so often, especially considering his posts are usually very thought provoking.

Anyway, the reason I’m writing all this was to share links to a few of the blog-authors I feel I’ve learnt the most from (you can see my Google Reader shared items here). These guys are super-smart (I mean clever rather than well dressed), and almost every post I read from them is a gem.

In no particular order:

  • Rob Conery – A fantastic, usually very entertaining writing style, with great content, especially on ASP.NET MVC. I’m also very jealous that he lives in Hawaii.
  • Jimmy Bogard – Every post is very clearly written and well thought out. A definite must-have on your feed-reader. Content generally covers things like SOLID principles, Agile development, and Doman-Driven Design. Author of to OSS tool AutoMapper.
  • Grey Young – A very inspiring blog, which I will read over-and over again. Content usually covers: DDD (specifically distributed domain-driven design), design patterns and agile development.
  • Jeremy Miller – I’ve got a lot of respect for this guy. He’s clearly a very intelligent chap. His blog often includes writing about: Software Architecture, Design Patterns, Test Driven Development, and Alt.Net. Author of the StructureMap IoC tool and FubuMVC.
  • Chad Myers – Chad’s posts are always very cohesive and well written, and along with Jimmy Bogard was one of the first blog-authors to inspire me with their work. His blog often covers topics like TDD, SOLID principles, and ALT.NET. Author of FubuMVC
  • Jan Van Ryswyck – Having only found Jan’s blogs on Elegant Code quite recently, it says quite a lot that he’s made it into my top list of blog-authors. His recent posts on fluent interfaces are typical of the inspirational pots he writes.
  • Ian Cooper – Ian’s blog contains some great material on persistence ignorance, nhibernate, TDD and BDD, and Linq. Less active than the bloggers above, but certainly worth adding to your feed-reader.

Other very good blog-authors to check out:

 

Whose blogs would you recommend?

Next Page »