CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter
Like CodeBetter.Com? Get more Stuff you need to Code Better at Devlicio.Us Devlicio.us

Functional .NET - LINQ or Language Integrated Monads?

As part of my talk at the Richmond Code Camp earlier in October, I had the opportunity to talk about how to implement functional aspects in C# 3.0.  This talk revolved around such concepts as from mutable to immutable, from inheritance to functional composition, and the mind shift that is required.  Part of this discussion involved very briefly a talk about monads.  It's a very misunderstood part of computer science and one of the most powerful concepts to learn.  Much like continuation passing style, this style is often maligned as a result.  But, let's work to change that.

 

What Is a Monad?

Monads come to us originally from category theory.  When monads applied to functional programming, they simply are a construction, given an underlying type system, embeds a corresponding monadic type system.  Simply put, the values you have become amplified values that are to be interpreted by the matching monadic type. 

The formulation of a monad comes in three parts:

  1. A type construction that defines for every underlying type, how to obtain a corresponding monadic type.  If the given type in F# is 'a, then the corresponding monadic type for an Identity monad would be I<'a>.  I'll cover more of what that means below.
  2. A unit function that maps the underlying type to a value in the corresponding monadic type.  In F# parlance, this maps to a Return function.
  3. A binding operation of polymorphic type, in F# parlance, (I<'a>) => ('a => I<'b>) => (I<'b>).  This maps to a Bind function given your monad builder.  If you look carefully at the signature of this, you might also note that the LINQ SelectMany follows this syntax.  Gee, what could that mean?  The bind operation follows four steps:
    1. The monadic structure exposes the underlying value of type 'a.
    2. The given function is applied to the underlying value to obtain values of type I<'b>
    3. The monadic structure exposes the underlying value of type 'b.
    4. The monadic structure is reassembled over the results, given a single value of type I<'b>

Simply put, a monad, unlike your normal function results, stores function results and side-effect representations. This allows side effects to be propagated through the return values of functions without breaking the pure functional model.  This is what makes it so powerful that it is a way to manage side effects.  Given a pure language such as Haskell, this is the way that any side effecting operation should be done.  Granted, there are impure ways of doing IO, but let's not go there.

There are some good sources of information on what monads are, including some great stuff from Brian Beckman:

Some examples of monads that are used frequently are such things as the maybe monad, identity monad, IO, collections and so on.  Let's move onto implementing some of these monads in .NET, whether it be F# or even C#.

 

Implementing in .NET

To implement the above mentioned monads, we'll take examples in both F# and C# to see that both can do the job.  Although I'll admit my preference for F#, C# can monads quite nicely using LINQ syntax.  But that sometimes means that the from and select keywords might be confusing.  But what people might not realize is that you are not limited to IEnumerable<T> inside LINQ.  Instead, you could have any backing type you want.  For example, I could have the identity type, maybe type, async type and so on.  We'll cover each one of those in detail in the following sections.

Anyhow, let's get started with the identity monad.

 

The Identity Monad

The easiest monad to understand is the identity monad.  This attaches no information to the underlying value, and instead only returns and transforms it. 

 

Implementing in F#

To implement in F#, we need to remember what's required for any monad builder.  That is the Bind, Return, Delay and Let functions.  Let's define our builder first with the given functions.

#light

type I<'a> = 'a

let bindI i f = f i
let resultI i = i
let delayI f = f()

type IdentityBuilder() =
  member x.Bind(i, f) = bindI i f
  member x.Return(i) = resultI i
  member x.Delay(f) = delayI f
  member x.Let(i, f) = bindI (resultI i) f
 

Now that our builder is defined, F# has a special way of representing monads in that you wrap them in curly braces with the given instance name of the monad builder.  In this case, I'll call it ident.

let ident = IdentityBuilder() 
let iValue = ident {  
                     let! x = 5 
                     let! y = 42 
                     return! x + y  
                   }                
printfn "%i" iValue

The above code allows me to define x and y and add them together.  The end result ends up being 47.  This looks pretty simple using this syntax, although this is what it ends up being behind the scenes:

let iValue = ident.Delay(fun () -> 
               ident.Bind(5, fun x -> 
                 ident.Bind(42, fun y -> 
                   ident.Return(x + y))))

As you can see, the syntax is much more simplified with the syntactic sugar that they give us.  This almost looks like LINQ in a way.

 

Implementing in C# 3.0

Now, what about C#?  What can we do there?  Actually, the answer is, that it's quite simple.  If you notice one thing about LINQ is the signature of the SelectMany method.  Let's look at the definition on the Enumerable class.

public static IEnumerable<U> SelectMany<T, U>(
  this IEnumerable<T> s,
  Func<T, IEnumerable<U>> f)
 

And if you look at the bind syntax that we used in our F# example, it's exactly the same signature.  That should tell us something that LINQ expressions can indeed be monads.  Now, let's implement the identity monad by first identifying the class and then the extension methods that make this work.

public class Identity<T>
{
    public Identity(T value) { Value = value; }
    public T Value { get; private set; }
}

public static class IdentityExtensions
{
    public static Identity<T> ToIdentity<T>(this T value)
    {
        return new Identity<T>(value);
    } 

    public static Identity<U> SelectMany<T, U>(
        this Identity<T> id, 
        Func<T, Identity<U>> k)
    {
        return k(id.Value);
    }

    public static Identity<V> SelectMany<T, U, V>(
        this Identity<T> id, 
        Func<T, Identity<U>> k, 
        Func<T, U, V> s)
    {
        return id.SelectMany(x => k(x).SelectMany(y => s(x, y).ToIdentity()));
    }
}

When we implement things for LINQ, we must be cognizant for the need of two SelectMany methods for various performance reasons to allow us to combine values.  Now that we've defined these methods, we can now use LINQ expressions to express our identity monad.

var identResult = from x in 5.ToIdentity() 
                  from y in 42.ToIdentity() 
                  select x + y; 
Console.WriteLine(identResult.Value);
 

As above the answer comes out to 47.  Let's move onto the maybe monad.

The Maybe Monad

The maybe monad is another popular monad type.  A maybe monad is very similar to the identity, yet a value may be missing.  In F# parlance, this translates to the Option<'a> type.  Let's go ahead and implement this in F# using our given option type.

 

Implementing in F#

Implementing the maybe monad is very similar to the identity monad.  The only difference being is the to differentiate between some value and no value specified.  We will determine that through pattern matching, as always.

#light

type M<'a> = option<'a>
 
let bindM d f = 
  match d with
    | None -> None
    | Some(v) -> f v
let resultM v = Some(v)
let delayM  f = f()
 
type MaybeBuilder() =
  member x.Bind(v, d) = bindM v d
  member x.Return(v)  = resultM v
  member x.Delay(f)   = delayM f 
  member x.Let(v, f)  = bindM (resultM v)
  

Once defined, we can now use our MaybeBuilder to define a simple use of our maybe monad.  Let's make sure we use None to denote that we are missing a value.

let maybe = MaybeBuilder()  
let mValue = maybe {  
                     let! x = Some(5)  
                     let! y = None  
                     return x + y  
                   }  
let option_to_string = function 
  | None -> "Undefined" 
  | Some v -> v.ToString() 
printfn "%s" (mValue |> option_to_string)

The result of course is "Undefined" because our y value is the None option type.  But, how might this work in C#? 

 

Implementing in C# 3.0

We can reuse a lot of our ideas from implementing this via extension methods.  I will go ahead and use the Option type that I've defined in my Functional C# project on MSDN Code Gallery.  From there, we can implement our SelectMany operations.

public static class MaybeExtensions
{
    public static Option<T> ToMaybe<T>(this T value)
    {
        return Option<T>.Some(value);
    }

    public static Option<U> SelectMany<T, U>(
        this Option<T> m, 
        Func<T, Option<U>> k)
    {
        return !m.IsNone ? Option<U>.None : k(m.Value);
    }

    public static Option<V> SelectMany<T, U, V>(
        this Option<T> m, 
        Func<T, Option<U>> k, 
        Func<T, U, V> s)
    {
        return m.SelectMany(x => k(x).SelectMany(y => s(x, y).ToMaybe()));
    }
}

Now that we defined our binding operations, we can move onto actually using the maybe monad.  Let's use the template that we defined up above for our identity monad and craft it to use our maybes.

var maybeResult = from x in 5.ToMaybe() 
                  from y in Option<int>.None 
                  select x + y; 
Console.WriteLine(
  maybeResult.IsSome ? maybeResult.Value.ToString() : "Undefined");
 

Once again, our result will be undefined as our y value has no real value at all.  Clear so far?  Let's move onto the List Monad.

 

The Collection Monad

The collection monad is another important monad type.  This monad is the heart and soul of LINQ and the way we use it to compute our lazily evaluated lists.  This monad strikes home as one of the most important to .NET developers.  Using LINQ to SQL, XML and such uses collections of various sorts to transform the data into other forms.

 

Implementing in F#

As before, we need to define our basic bind, let, return and delay functions in order for the monad to work in F#.  Let's define the list monad to use seq<'a>.  This way, I can lazily evaluate my results and yield them when I need to.  For the bind and result statements, I'm using a sequence expression to yield the appropriate values.

#light

let bindL l f = 
  seq{for x in l do
        for y in f x do
          yield y}
let resultL l = seq{ yield l }
let delayL f = f()

type SeqBuilder()
  member x.Bind(l, f) = bindL l f
  member x.Return(l) = resultL l
  member x.Delay(f) = delayL f
  member x.Let(l, f) = bindL (resultL l) f
 

Now that we've defined our monad builder, let's implement this to add the values from each collection to each other.

let seqMonad = new SeqBuilder()
let sValue = seqMonad {
                        let! x = {1..3}
                        let! y = {4..6}
                        return x + y
                      }
sValue |> Seq.iter(fun x -> printfn "%i" x)

Our results will be the addition of each number in each list to each other.  So, in turn, I will get 9 numbers in total with a value of 5 6 7 6 7 8 7 8 9.

 

Implementing in C# 3.0

To view the bind methods, simply open the Enumerable class to view the SelectMany implementations.  This will get us started in looking at a C# equivalent to the list monad we did above.  A simple representation might look like this.

var sValues = from x in Enumerable.Range(1, 3)
              from y in Enumerable.Range(4, 3)
              select x + y;
foreach (var sValue in sValues) Console.WriteLine(sValue);
 

And we now realize the answers between the two are exactly the same.  No special magic required for list monads.

 

The Asynchronous Monad

One of the most often used monads in F# is the asynchronous computation expression.  This allows us to use non-blocking calls to download resources, whether it be files, web request, WCF calls and so on.  This is where monads become really useful for .NET developers who want to explore a little outside the box in ways of thinking about monads. 

 

Implementing in F#

We get the asynchronous computation expressions out of the box with F#.  This allows us to easily create asynchronous computation expressions which I talked about earlier here.  But, let's look at one example of downloading the HTML from various web sites in parallel with non-blocking calls.  What might that look like?

#light 

open System.IO 
open System.Net 
open Microsoft.FSharp.Control 
open Microsoft.FSharp.Control.CommonExtensions 

let get_html_async (url:string)
  async { 
          let request = WebRequest.Create(url) 
          let! response = request.AsyncGetResponse() 
          let stream = response.GetResponseStream() 
          let reader = new StreamReader(stream) 
          let! text = reader.AsyncReadToEnd() 
          return text 
        } 
         
let urls = ["http://live.com"; "http://google.com"; "http://codebetter.com"] 
let textResults =  
  Async.Run(Async.Parallel [for url in urls -> get_html_async url]) 
textResults |> Seq.iter(fun textResult -> printfn "%s" textResult)

As you can see, we're creating a request, getting the response, creating a reader, and reading all the way to the end asynchronously.  As you may note, there is a difference between let! and let.  The let! uses the Bind method whereas the let uses the Let method of AsyncBuilder.  What I'm able to do here is take three websites, and download their HTML and display within a short amount of time.  Imagine if I had to write that using IAsyncResult classes and such.  That wouldn't be ideal!  But, can C# partake in this?

 

Implementing in C# 3.0

The question I asked is that can we take advantage of the F# asynchronous computation expressions in C#?  The answer, surprisingly is YES!  I had the opportunity to talk to F# developer, Brian McNamara, on this very subject.  Back in May, he posted a quick example of using the F# libraries from C#.  There is a bit of work required to do this, but it pays off handily.  I'll cover the exact details in my next post of how to do it.  But, in the mean time, imagine if we could download HTML from three websites simultaneously using LINQ?  Here's what the code that does exactly that looks like.

Func<string, Async<string>> get_html_async = url =>
   from _ in AsyncExtensions.StartWorkflow
   from request in WebExtensions.AsyncCreateWebRequest(url)
   from response in request.AsyncGetResponse()
   let reader = new StreamReader(response.GetResponseStream())
   from urlText in reader.AsyncReadToEnd()
   select urlText;

var urls = new[] { "http://live.com/", "http://www.google.com/", "http://codebetter.com/" };
var urlTexts = Async.Run(
    Async.Parallel(from url in urls select get_html_async(url)), Option<int>.None, Option<bool>.None);
Array.ForEach(urlTexts, Console.WriteLine);
 

How simple is that?  Well, we have to put some backing to some of these methods in order to make them asynchronous, and I will cover exactly what that is in the next post.

 

Wrapping it Up

What about such things as the IO monad?  Well, that's more of a language construct that is enforced by the compiler.  I would like to see something similar to this in F# going forward, so that we could better manage our side effects.  Using such technologies as Spec# to statically verify the behavior is important.  But, once again, that's another post.

I hope I helped to alleviate some of the confusion around monads.  More importantly, I hope you know more of how and when to use them.  In the next post, I'll follow up with the actual implementation of the asynchronous computation expressions in C# 3.0.  Giving us the ability to have parity with F# is really powerful and attests to the power of LINQ (and monads of course).  Stay tuned!

Sharing code styles in ReSharper

Have just started a new project and my first task is some Silverlight thingamajig that I'm sure I'll go on about ad nauseum in the coming weeks. But first, let's talk about some ReSharper settings.

My very first check-in in the code base was a ReSharper code style settings filimagee. This is a way of allowing everyone on the team uses the same settings. The documentation for this feature is here though it's a little out of date. To the right is a screenshot from version 4.1.

This is somewhat important for me because I have some different ideas about whitespace than most people. And I don't want to impose my will on someone else. (At least not so crudely.) Nor do I want to alter my own personal projects just because everyone else likes to have all their code scrunched up together so that parentheses and curly braces essentially take the place of spaces and you need a &*%$ Little Orphan Annie Decoder Ring to parse out the actual meaning of these god-forsa--...

Ummm...let's just say I'm a little set in my ways and move on...

By default, your ReSharper settings are global across all projects. The two other settings are: a) Shared across the team, per solution, and b) Not shared, per solution, stored in a file.

Both are very useful in teams where developers work on more than one project, such is the case here. The other obvious example is open-source projects. Here's a quick run-down of each.

Shared across the team, per solution

Here, the code style settings are stored in a .resharper file in the same folder as the .sln file. This is ideal for a non-intrusive way to enforce coding standards on a project. Developers download the source and go. They may not even know it's using a shared code style.

MvcContrib uses this mechanism to enforce standards. I'm not on the new project because I've added .resharper files to my global SVN ignore list and I'm too lazy to change it. Plus, I'm not quite sure how it works between ReSharper 4.0 and ReSharper 4.1. I.e. is it able to manage users that use 4.0 and others that use 4.1? And what happens when one user changes the settings inadvertently? As an example, I just updated to the latest MvcContrib, opened it up, and now I have MvcContrib.4.1.resharper checked out for some reason.

So instead, we're using the next option.

Not shared, per solution, stored in a file

With this option, you explicitly tell ReSharper where the settings are stored. It requires a little more work to set up. Unlike the previous option, the developer needs to go into the ReSharper settings and physically select this option and navigate to the file. It takes an absolute path, not a relative one.

I'm guessing that this is because the settings to tell ReSharper which option to use are stored in the .resharper file, which as I've mentioned, we're not including in source control.

Both options give you the ability to set standards like naming conventions, spacing, and, theoretically, how to re-order methods, fields, and properties within your class. I say theoretically because this particular one (under Type Members Layout) seems a little eccentric. I had to import the settings from the code style file, then shut down and restart the solution for them to take. And when I make changes to this section, they aren't always reflected in the settings file.

None of this guarantees that your code will be consistent. After all, not everyone may have ReSharper. Also, I'm pretty sure the settings to auto-format are machine specific so someone could turn them off and then you have to rely on them to do an explicit auto-format before they check in. Furthermore, it appears that formatting profiles are also machine-specific, so even if you create one that runs through all your rules, re-orders things, and otherwise cleans up when you press Ctrl+Shift+Alt+F, that won't get propagated to anyone else's machine.

Kyle the Styled

Listen to your users

 

While listening the users to improve the usability of your product seems to be a controversial issue, I am leaning toward the Listen to user camp. My opinion is biased by the fact that I have the exceptional chance to share the same job and same concerns with users of the product I am responsible for. As all of us in the NDepend team, our users are developers and architects with a solid interest in software quality and maintainability.

 

I recently got a nice occurrence of the Listen to your users tenet. It is about the Structural Dependency Matrix, one of the most polished feature of NDepend. It has been released 2 years ago and since then, we are continuously improving it. We believe that the matrix is a unique tool to detect code structural flaws, to understand and explore the real architecture of a code base and to forecast the cost and feasibility of large refactoring. The matrix works hand-in-hand with the graph view, the CQL language and most other features of NDepend. It comes with dozens of options categorized with the Make the simple things simple and hard things possible idea in mind. It has been profiled to the point where every action execute in real time, even on hundreds of thousand’ cells matrix representing inter-dependencies of millions of lines of code. We dog-food it daily to improve the structure of the NDepend code itself. Despite all this work and expertise, a user came to us recently with a very useful option that we never thought about! The ice on the cake is that everything was here to let us implement and test it readily.

 

The idea consists in letting the user remove empty rows/columns. It is especially useful when the dependency matrix is sparse. Here is a matrix representing the coupling between the 113 types of the namespace System.Drawing and the 205 methods of the class System.String. This matrix is sparse and not very handy to browse the who uses who in this coupling.

 

 

 

Here is the same coupling where empty rows and columns have been removed. The sparse (113x205) matrix became a dense (27x29) matrix. It is now much easier to gather useful information about the System.Drawing to System.String.

 

 

 

 

I believe that such a dense matrix represents the optimal way to browse complex coupling. The following coupling graph that shows the exact same information is partially unreadable:

 


 

 

The questions are why we didn’t think of this feature before and why no user asked for it so far? The answer is that actually this feature already existed more or less, through the possibility of opening a dependency within the matrix by keeping only involved code elements. Here is an illustration of this possibility:

 

 

It seems that everyone got used to this keep only involved code element feature that hided the need for removing empty rows or columns in a bit more complex scenario. Hopefully a fresher user view opened our eyes on the usefulness of this feature.

 

Concerning the Listen to users tenets, its veracity certainly depends on your users qualification. In the past, I have been team leader for a software PC station that tracked expensive remote assets such as luxury cars and loaded trucks. Users of the program were security guards that knew more about guns than about computers. Obviously, at that time I didn’t think that it was a good idea to listen to users to improve the usability of the PC station. But observing them using it was certainly a good idea.

 

 

Fitnesse and the 3-way meeting

Jeremy posts in his blog about his replacement for StoryTeller about the pain of FIT based tools. We have been using Fitnesse on the current project and while there has certainly been pain, I think that the pain has been that all tests experience when they start to run the system end-to-end. Suddenly all those technology framework concerns we eliminated in TDD so that we could just focus on testing our domain model, come back into play. Once again we are dealing with setting up and tearing down databases, touching the file system etc.

Our decision to use Fitnesse on this project came from two forces. First was the general lack of satisfaction with our functional testing process. Up to now functional testing had been a combination of xUnit integration tests, custom built tools, and manual testing. Previous attempts with FIT has always drawn a blank. The result was that 'release hardening' took a lot longer than we would desire and smelt of waterfall style testing phases. Second, we wanted to have a better way to communicate the acceptance criteria for the story from the users to BAs, testers and developers such that we were doing story test driven development  or customer test driven development and pushing our code from the agreed acceptance criteria.

We got a real lift in this direction from Gojko Adzic. Gojko spoke for us at London .NET User Group. I got answers to a lot of the fixture issues I had had with FIT.  After that talk I read through Gojko's book on Fitnesse, which reinforced and clarified the message, and was re-enthused by this tool. It's far from perfect,  roll on better tools from Jeremy, but it does give us the placeholder for the story acceptance criteria to drive development.

Like everything it is taking a while for us to refine our use of Fitnesse. One key change for us came from internal conversations and discussions with Gojko - the idea of a three-way meeting. Gojko came in to deliver this presentation at my current outfit (worth watching the video) which explains his thinking. To give my understanding of Gojko's point: the important part of using a tool like Fitnesse for story test driven development is the communication that occurs between customer and implementers. In a case where you may have customer -> BA -> developer -> tester in the mix, the potential for lossy information transfer and misunderstandings is large. Remember the classic swing cartoon? While agile provides some relief by making sure that requirements->development->testing all happen together, thus shortening the feedback loop that leads to failed requirements intepretation, simple 'transcription' errors between people can lead to issues. By getting everyone to review an executable form of the specification then the possiblity of one of us going astray is far less. To facilitate this we now begin work on any story within the iteration with a three-way meeting between BA->developer->tester to ensure that everyone agrees on what the acceptance criteria for the story are. Of course if there are more stakeholders, you may need to increase the size of this meeting. The Fitnesse test becomes a record of that conversation that everyone involved can check, but in many ways the fact that using a tool like Fitnesse forces us to have the conversation and reach agreement may be as important as the result - the excutable specification - is.

The result of the three-way has been that we are finding it easier to implement Fitnesse tests. We still have some problems of our own making (related to how we seed data for tests), but this seems to have removed a lot of the pain around these for us. The suggestion might be that a number of our issues with story test tools has been simply a reflection of problems communicating requirements.

StoryTeller is Dead. Long live StoryTeller!

I worked on and off again for about 2 years on a new OSS project called StoryTeller.  My original goal was to create a better editing and test management tool for Fit tests than the FitNesse Wiki approach.  I had *some* success, and I was able to use the rough StoryTeller UI on a couple projects.  Even in its rough form, I think StoryTeller was already better than FitNesse (as long as you knew what things on the UI that were not ready to be clicked on;)  All the same though, I haven’t found the tool to be all that successful, and my enthusiasm for the project has waned.  All of this is just an explanation for me announcing that I’m abandoning the original StoryTeller approach altogether.

For those of you who have asked me where the old code went, I’ve shelved the old code in a new SVN branch at:  http://storyteller.tigris.org/svn/storyteller/branches/old (for anonymous access, the user id is “guest” and the password is blank).

 

I still believe in Fit from a conceptual standpoint, but I’ve simply had it with the Fit mechanics.  Last week I started StoryTeller over from scratch, but this time I’m ditching Fit altogether and building a new test automation engine from scratch.  I don’t have a lot of information on it at the moment, but I’m hopeful that I’ll be able to demonstrate the new StoryTeller in action as soon as KaizenConf in three weeks. 

 

Some Facts:

  • StoryTeller is being conceived as a dedicated tool for crafting external testing DSL’s, and a UI for editing that DSL.  The test editing will be done mostly in forms rather than in text.  The point is to make test editing as guided as possible to make editing more efficient and less error prone.
  • I’m building a brand new testing engine from the ground up.  I think the new engine will make it easier for .Net developers to write the Fixture code and make it much easier to expose the metadata that the UI will need to create the test visualizations and test editors
  • I’m pitching StoryTeller as an automated testing tool that creates human readable specifications rather than a tool to automate specifications.  It’s a subtle shift in focus, but my experience has been that analysts and business partners either can’t or won’t participate in Fit test writing.  Hell, getting business people to even look at Fit tests has been a trial.  StoryTeller New is being built to be as easy to use as possible for reasonably able developers.  Specifically, it’s getting built for my team and my project with the hope that it will be useful for somebody else too.
  • The UI will be built from the ground up in WPF.  I’m hoping to use the UI for sample code in my book on UI patterns.  I think WPF is miles ahead of WinForms in its ability to do dynamic layout, and I’m going to push that ability as far as it will go.

 

 

Why I’m abandoning the FitnesseDotNet engine

I feel like I owe a bit of an explanation for this decision.  You can find most of the reasoning at Why I’m Suddenly Down on Fit/FitNesse.  The final nail in the coffin for me was way too many conversations like the following:

“Well first, make this a ColumnFixture and override the Execute() and Reset() methods.  Then override the DoRows() method, but be sure to call base.DoRows() before you add your code.  Then write a DoFixture class with a method that returns your new ColumnFixture”

Blech.  I love the concept behind Fit, but the implementation leaves something to be desired.  It’s just plain weird, and far too laborious to craft Fixture classes.  We partially beat the issue by doing quite a bit of code generation, but I’m in the camp that says code generation is a border line code smell.  In bullet point form, here’s why I think it’s time to move beyond Fit:

  • Test writing with Fit is very failure prone.  Fit is very sensitive to formatting errors and there isn’t a good way to discover syntax errors without running the tests.
  • The test management tools for Fit suck
  • The extensibility mechanisms (ICellHandler etc.) are odd and hard to understand, but understand them you must
  • It simply takes far too much knowledge about how the Fit engine works to write Fixture classes.  Very few people are willing to make that investment. 
  • The FitnesseDotNet engine has become far too coupled to FitNesse.  The last time I pulled a new build, I had to fork the code to get it to run outside of the FitNesse Wiki engine. 

 

Other Things

There’s a lot of things shaking out there in the world of test automation.  I’m not sure that I’d say that StoryTeller will be a direct competitor to the xBehave and xSpec tools.  ThoughtWorks just released Twist, and it looks roughly like what I’m envisioning, but the TW clowns made it Java only and tied it to Eclipse (and I detest Eclipse).  Bob Martin just announced a similar sounding tool called “Slim” as an alternative to the Fit engine for FitNesse, but it doesn’t seem to address the issues I have with Fit and FitNesse.  There’s also a chance that the textual DSL tooling in Oslo could do what I want StoryTeller to do.  I’ll keep an eye on all of these just in case.

Learning On A Project

 There has been a fair amount of activity in the blogsphere to Roy's original post about increasing TDD adoption. Roy updates some of the reaction here and here. Udi comments on my reaction that the most important thing is to being writing tests and then learn how to write them better. Udi questions whether it is right for us to expect customers to allow us to learn on their time. And Casey Charlton makes a similar point in comments on Tim's blog. There has been a fair amount of discussion as to how we teach TDD over at the TDD mailing list too.

I have not changed my position in response to these comments, but I did want to talk a little about change and learning.

Embrace Change

The XP strapline was 'Embrace Change' and it remains, to me, at the core of key alt.net ideals like Continuous Improvement. Our field is contantly changing. New technologies, practices, and methodologies emerge with alarming frequency. Sometimes the pace of new developments can seem frightening. We can have two reactions to such change: resist it or embrace it. The danger with resisting is that we stagnate, stuck in the comfort zone of what we know. I see a lot of resistance to ideas like TDD simply because people do not feel comfortable with changing practices. Alt.Net is for me about the idea of embracing change, of continuous improvement. Embracing change for its own sake has its own dangers of course. The urge to try the latest thing can lead us into peril if we fail to critically evaluate its value to us.

My experience is that change usually occurs when the pain of existing practice becomes so great that it pushes aside the resistance to change. There must be a better way, we think. My experience of test-first development is that the pain of the test and debug phase at the end of waterfall projects pushes people to look for solutions. Solving issues here improves delivery, reduces cost, and increases customer satisfaction. As the cost of that phase rises and projects slip due to the uknowable length of making the project fit for release, the customer begins to feel the pain of older approaches. The promise of test-first approaches, building quality into the manafacturing process instead of in a seperate QA step, becomes attractive enough that people trial the new ideas. There is business value in agile processes, which can be demonstrated by solving the typical pain problems that organizations not using agile development practices have.

My point on the most important step being to start testing, over worrying about following best testing practice is that the value of building quality in can be quickly seen. Once a team realizes that value in test first approaches they will buy in to learning how to do them better. But its that first buy in that counts. People worry about whether test-first is about testing or design. It's simply about quality - which includes both of those and more.

Of course there is a leap of faith on the first project. My experience is of pilot projects which trial these new approaches and compare results against existing processes to persuade key decision makers of their value. Often we try new techniques or technologies on lower-profile or even internal to IT projects to assess their value over high risk high profile work. This is not always the case. Once we buy into newer technologies or practices we may choose to up our game and improve our use of them on high profile projects because people have the motivation on them to try something new.

While I agree with the idea that developers have an obligation to their own professional development, there is always a difference between learning a new skill  and improving our ability with that skill through practice. I can read volumes on TDD best practices, but it is only for trying it out in anger, at some scale, that I can master it. For many, it is only practice that provides the encouragement to learn more. This kind of practice always has to be on the job, in this and in every other field. You can do all the book learning and training you want - ultimately you have to practice to master a skill. We train our developers when we want them to work with new third-party products that provide us with document management, rules, feeds etc. Why would we not want to train them in better practices? I have and continue to give training at my current organization and would expect to continue to do so. I have received training from my current organization. This is occurs in all professions.

 At a discussion in our recent London altnetconf Alan Dean pointed to the observation that agile practices often depend on agents of change, and they can ebb and flow within those organizations with the arrival and departure of such agents. The key to change is often individuals who learn and practice new techniques, or who bring experience of those techniques from other organizations. I love working with new people who have strong agile backgrounds because they bring with them fresh ideas and new perspectives to challenge me.

But to gain from thier experience we have to accept that we will need people to accept change and work in new ways. And they may not get it right at first. There will be a learning curve.That for me is why reflection workshops/sprint reviews are so important. They create the discipline of examining our use of practices and techniques and encourage us to get better at them. So the team that picks up TDD and just does it has plenty of opportunity to see the pain of talking to the Db or touching the file system, look for solutions and correct their course. Will there be additional cost to learn. Of course! But the cost of not learning is far higher.

 

 

Setter Injection in StructureMap 2.5

I know this isn’t the most exciting post I’ve ever written, but I’m blogging the new StructureMap 2.5 documentation as I create it.  I’ve done quite a bit of work in StructureMap 2.5 to extend the support for Setter Injection and it’s worthy of some attention for new and old StructureMap users.  *I* still think that Setter Injection is sub-optimal, but there are times when it’s necessary.  I’ll make a separate post later on how some of the newer setter injection support can be used to create an equivalent to Windsor’s logging facility.

 

Setter Injection

StructureMap supports two forms of Dependency Injection:

  1. Constructor Injection -- "Pushing" dependencies into a concrete class through constructor arguments.
  2. Setter Injection -- "Pushing" dependencies into a concrete class through public properties.  The "Setter" nomenclature is taken from Java where properties are getSomething() and setSomething(value).

You can certainly mix and match Setter Injection with Constructor Injection on the same classes, but Constructor Injection will always be used (except for empty constructors) and Setter Injection has to be explicitly configured.  See Martin Fowler's discussion on Constructor versus Setter Injection for more information.  My feeling has always been that Constructor Injection is preferrable from a design perspective.  When you exclusively use Constructor Injection, the code is somewhat more self-documenting because the constructor arguments will clearly delineate the dependencies of a concrete class.  It's also important to think about the constructor method of a class being a contract.  If you satisfy all of the arguments of the constructor method, the class should be ready to function.  Relying on Setter Injection can make a class harder to use because it isn't always obvious which setters need to be created externally to use the class.  Of course, not using any form of Dependency Injection can be the worst answer because then you have no idea what it really takes to bootstrap the service.

Despite my personal distaste for Setter Injection, I gave into user demand and greatly increased StructureMap's support for Setter Injection -- and promptly found that support to be more useful than I thought it would be.

 

Using Setter Injection

Setter injection is a pattern of "injecting" dependencies via public properties.  Setter Injection with StructureMap is somewhat a second class citizen, but this is partially by design.  My strong recommendation is to use constructor injection for all code that you control, and save setter injection strictly for classes from external libraries where you do not have any control.  As a summary, these are the Setter Injection features that are described in detail below:

  • By default, all public "Setters" are optional, meaning that these setters will only be set if they are explicitly configured for a specific Instance
  • StructureMap can be directed to "auto wire" a property for a given Instance
  • Setters can be made mandatory by decorating the property with the [SetterProperty] attribute
  • Any type that StructureMap can use in constructor arguments can be used for setter properties
  • StructureMap can be directed to automatically inject the default value for any property of a given type.  This was added primarily for "optional" dependencies like logging.
  • The StructureMap diagnostic tools will check for missing Setter values

 

Configuring Primitive Setter Properties

Ok, now that you've read that I don't believe that setter injection is a good idea, but you're bound and determined to use it anyway, let's talk about how to do it with StructureMap.  Let's say we have this class with a string property called "Name":

    public class OptionalSetterTarget

    {

        public string Name { get; set;; }

    }

I can specify the value of the "Name" property in the configuration API like this:

        [Test]/p>

        public void optional_setter_injection_with_string()

        {

            var container = new Container(r =>

            {

                // The "Name" property is not configured for this instance

                r.InstanceOf<OptionalSetterTarget>().Is.OfConcreteType<OptionalSetterTarget>().WithName("NoName");

 

                // The "Name" property is configured for this instance

                r.ForConcreteType<OptionalSetterTarget>().Configure

                    .WithProperty("Name").EqualTo("Jeremy");

            });

 

            container.GetInstance<OptionalSetterTarget>().Name.ShouldEqual("Jeremy");

            container.GetInstance<OptionalSetterTarget>("NoName").Name.ShouldBeNull();

&        }

In the case above I specified the value for the "Name" setter directly by embedding the property value directly with the WithProperty("Name").EqualTo("Jeremy").  You could also retrieve the value for the property from the AppSettings portion of a .Net application config file like this with the WithProperty("Name").EqualToAppSetting("name") syntax.

            var container = new Container(r =>

            {

                r.ForConcreteType<OptionalSetterTarget>().Configure

                    .WithProperty("Name").EqualToAppSetting("name");

            });

In both of the cases above the property name is designated by a string.  Using strings to designate property names is always going to be somewhat problematic, so there's a new option in 2.5 to specify property values with a Lambda expression (inspired by this post from Udi Dahan) using an Action<T>.

                r.ForConcreteType<OptionalSetterTarget>().Configure

                    .SetProperty(x => x.Name = "Jeremy");

The value of the Lamdba expression mechanism is that it makes the configuration static-typed with all of the advantages that static typing brings.  This action is executed on the object after creation.  Technically, this mechanism can be used to do anything to the new object before StructureMap returns the new object to the code that requested it.  There is no limitation to the number of Action<T> handlers you can use.

 

Configuring Setter Dependencies

Let's say you have a class that has a public property for a singular dependency and another public property for an array of dependencies.

    public class ClassWithDependency

    {

        public Rule Rule { get; set; }

        public Rule[] Rules { get; set; }

    }

I can explicitly configure what gets injected into the "Rule" property for a specific Instance of ClassWithDependency like this with the .SetterDependency<T>() method that will look for the first public setter of type T:

                r.ForConcreteType<ClassWithDependency>().Configure

                    .SetterDependency<Rule>().Is(new ColorRule("Red"));

or for cases where a class may have multiple public setters of the same type, you can specify the exact property with an Expression (.SetterDependency<T>( expression ) ):

            var container = new Container(r =>

            {

                r.ForConcreteType<ClassWithDependency>().Configure

                    .SetterDependency<Rule>(x => x.Rule).Is(new ColorRule("Red"));

            });

 

"Auto Filling" a Setter Dependency

Sometimes all you want to do is to simply say "fill in this property for me."  That's what the code below does for the "Rule" property with the .SetterDependency<Rule>().IsTheDefault() syntax:

            var container = new Container(r =>

            {

                r.ForConcreteType<ClassWithDependency>().Configure

                    .SetterDependency<Rule>().IsTheDefault();

 

                r.ForRequestedType<Rule>().TheDefault.Is.Object(new ColorRule("Green"));

            });

   

For certain dependency types you might want StructureMap to automatically fill any public property of that type.  The first usage that comes to mind is logging.  Let's say that we have an interface for our logging support called ILogger.  We can specify that any concrete class that has a public property for the ILogger type will be filled in construction with code like this (FillAllPropertiesOfType<ILogger>()):

            var container = new Container(r =>

            {

                r.FillAllPropertiesOfType<ILogger>().TheDefault.Is

                    .ConstructedBy(context => new Logger(context.ParentType));

            });

Now, if I have some classes like:

    public class ClassWithLogger

    {

        public ILogger Logger { get; set; }

    }

 

    public class ClassWithLogger2

    {

        public ILogger Logger { get; set; }

    }

Now, when StructureMap builds new instances of these classes above the Logger properties will be filled automatically without any explicit configuration for either type.  Here's a sample from the unit tests that constructs objects of both ClassWithLogger and ClassWithLogger2 and verifies that the "Logger" property was filled for both types without any further configuration.

 

            container.GetInstance<ClassWithLogger>().Logger.ShouldBeOfType<Logger>();

            container.GetInstance<ClassWithLogger2>().Logger.ShouldBeOfType<Logger>();

 

 

 

Defining Setter Properties with Attributes

Just use the [StructureMap.Attributes.SetterProperty] to denote properties that need to be filled by StructureMap.  Marking a property with the [SetterProperty] makes the setter mandatory.  StructureMap will throw an exception if the "ShouldCache" property isn't specified for the concrete type shown below.  If the "Provider" property isn't explicitly configured, StructureMap will use the default instance of IDataProvider for the "Provider" property (or throw an exception if StructureMap doesn't know how to build the type IDataProvider).

    public class Repository

    {

        private IDataProvider _provider;

 

        // Adding the SetterProperty to a setter directs

        // StructureMap to use this property when

        // constructing a Repository instance

        [SetterProperty]/p>

        public IDataProvider Provider

        {

            set

            {

                _provider = value;

            }

        }

 

        [SetterProperty]

        public bool ShouldCache { get; set; }

    }

 

Defining Setter Properties in Xml

Setter properties can be defined in the Xml configuration by explicitly directing StructureMap to use setter properties while building a concrete type.  In the Xml, Setter configuration is done with the exact syntax as constructor arguments.  For example, the "Name" property of the OptionalSetterTarget class shown in previous sections can be set just like a constructor argument in an Xml node:

  <StructureMap MementoStyle="Attribute"

    <DefaultInstance

        PluginType="StructureMap.Testing.Pipeline.OptionalSetterTarget, StructureMap.Testing"

        PluggedType="StructureMap.Testing.Pipeline.OptionalSetterTarget, StructureMap.Testing"

        Name="Jeremy" />

  </StructureMap>

 

Setter properties can also be designated as mandatory setters with the <Setter> node in the Xml configuration.  From the unit tests, I have a class called OtherGridColumn that exposes several properties:

    public class OtherGridColumn : IGridColumn

    {

        public IWidget Widget { get; set; }

 

        public string ReadOnly

        {

            get { return "whatever"; }

        }

 

        public FontStyleEnum FontStyle { get; set; }

        public string ColumnName { get; set; }

        public Rule[] Rules { get; set; }

        public bool WrapLines { get; set; }

        public bool Displayed { get; set; }

        public int Size { get; set; }

    }

 

I can direct StructureMap to make the properties on the OtherGridColumn class mandatory in a <Plugin> node for OtherGridColumn.  This probably isn't necessary with the new optional setter injection capabilities, but it is still valid and the equivalent of using the [SetterProperty] attribute.

  <PluginFamily/span> Type="StructureMap.Testing.Widget5.IGridColumn" Assembly="StructureMap.Testing.Widget5" DefaultKey="">

    <Plugin Assembly="StructureMap.Testing.Widget5" Type="StructureMap.Testing.Widget5.OtherGridColumn" ConcreteKey="Other">

      <Setter Name="ColumnName" />

      <Setter Name="FontStyle" />

      <Setter Name="Rules" />

      <Setter Name="Widget" />

      <Setter Name="WrapLines" />

    </Plugin>

  </PluginFamily&>

More Posts Next page »


Our Sponsors