February 2008 - Posts

Update:  Added more topics
Today we have another installment of the Adventures in F# - F# 101 series.  This time we're going to cover more functional programming basics and hopefully cover some pretty interesting things along the way and compare them with normal imperative style programming.  I believe that functional programming, mixed with imperative constructs is the natural evolution of the .NET framework, and indeed the future of it.  Like I've said before in previous posts, the languages are starting to converge on a mix of it with C# 3.0 and beyond. 

So, let's get caught up to where we are today and where we came from:
On a side note, as you read these, Dustin Campbell also has a series that I've linked before, but a few have come out recently that you may want to pay attention to.  What's great about the F# community, although small, is very willing to help each other out in forums, emails, chats and so on.  Check out hubFS for that kind of community.  You might even find some product team members there.  Anyhow, before shiny things came along, let's get back to Dustin here and his "Why I Love F#" series:
And the list goes on from there.  Drink it up!

So, let's move onto the topics for today.  Today we will cover the following areas:
  • Scoping it Out
  • Recursion, Recursion, Recursion
  • Staying Anonymous
Scoping it Out

Scoping of variables is a common thing inside any programming language and really no different in F# at all.  Remember that identifiers can be either values or functions themselves.  The only thing to me that is interesting about F# is that you can redefine your identifiers.  By default, your identifiers are immutable unless otherwise specified in functional programming languages.  So, we're not going to change the value, but instead redefine.  And what's more interesting, is that you can change the type on the fly as well with the redefine, so be careful!

#light

 

let message =

  let temp = "Foo"

  let temp = 1

  let temp = "Bar"

  temp


So, this one works and quite simply just by redefining what temp is.  If we pop open Reflector, here's what it boils down to in C#:

public static void _main()
{
    message@3 = "Bar";
}

As you can see from there, it refactored that code out that we didn't need at all.  It was a pretty stupid example, but interesting nonetheless. 

Recursion, Recursion, Recursion

Recursion is one of those computer science lessons that everyone should have learned back in their early CS days.  This was taught in line with pointers, reference, hex/octal math, linked lists and so on.  I certainly hope they still teach that stuff nowadays with Java and .NET now the mainstays in universities.  Anyhow, if you didn't have that luxury, it's basically where you have a function that calls itself in order to return an answer.  Some of the classic examples of this are computing factorials, Fibonacci sequences and so on.    Of course recursive functions can have their downsides including blowing out the call stack if the recursion gets too deep or gets into an infinite loop, so it's always a good thing to test for these sorts of things. 

F# treats recursive functions just a bit differently than regular functions.  In fact, in order to make a function act recursive, you must mark it as such using the rec keyword.  This allows you to call that function within that function, else it will give a syntax error.  So, let's step through a few examples.

Let's start out with the classic Fibonacci sequence.  To do this in traditional imperative programming, it looks something like this in C# 2.0:

static int Fib(int i)

{

    if (i <= 1)

        return 1;

 

    return Fib(i - 1) + Fib(i - 2);

}


Ok, so that's old school to me.  Instead, since I mentioned that C# is going more towards a functional programming style, let's go ahead and do that again using anonymous functions (System.Func) instead.

Func<int, int> fib = null;

fib = i => i > 1 ? fib(i - 1) + fib(i - 2) : 1;


Ah, much cleaner.  But, let's take this to F# and use pattern matching instead of just the normal if/else control structure, just to be on the wild side.

#light

 

let rec fib n =

  match n with

  | 0 -> 1

  | 1 -> 1

  | n -> fib(n-2) + fib(n - 1)

 

let fib10 = fib 10

printfn "10th Fibonacci 10 %i" fib10


Ok, so let's throw a few more logs onto the fire with a couple more, one with recursing all files in a given directory (yes, I know you can do it with Directory.GetFiles, but this is more fun), and computing a factorial.

#light

 

open System.IO

 

let rec recurseDirectories x =

  let fileList = new ResizeArray<string>()

  fileList.AddRange(Directory.GetFiles(x))

  let subDirs = Directory.GetDirectories(x)

  subDirs |> Seq.iter(fun x -> fileList.AddRange(recurseDirectories x))

  fileList

 

let directories = recurseDirectories @"E:\Work"

directories.ForEach(fun x -> printfn "%s" x)

 

let rec fac n =

  match n with

  | 0 -> 1

  | n -> n * fac (n - 1)

 

let fac10 = fac 10

printfn "Factorial of 10 %i" fac10


In the recurseDirectories function, I was being a little tricky and using a mutable structure.  The ResizeArray<T> is actually just a rename of the List<T> generic from the regular CLR.  As you can note, I'm not using any control functions for doing so such as foreach loops, etc.  Instead, I'm using the Seq collection inside of F# proper and I'm sure I'll get to that later.  And yes, there are probably more ways of doing these, but these are pretty good nonetheless.

Staying Anonymous

As you saw from above, I used the keyword fun.  What that is, is using an anonymous function.  This is much like in C# using the System.Func structure but with different underlying base classes underneath.  Some simple examples of creating anonymous functions are just that, for iterating over a block like above.  We also can do something else like doing some simple examples such as below:

#light

 

let a = (fun b c -> b * c) 12 13

printfn "%i" a


We can also use tuples with this as well.  This means that you must specify all parameters up front.  You can only do pattern matching when using this style.  If you need to supply multiple arguments to this, go ahead and use Currying, which we talked about last time.  Below is a simple example of the above code:

#light

 

let a = (function (b, c) -> b * c) (12, 13)

let z = (function y -> function x -> y * x) 12 13

printfn "%i" z

printfn "%i" a


And this even can apply when using .NET classes such as the ResizeArray<T> such as this quick example:

#light

 

let stringList =

  let temp = new ResizeArray<string>();

  temp.AddRange([|"Hello"; " "; "Cleveland"|])

  temp

 

stringList.ForEach(fun x -> print_string x)


Wrapping It Up


Well, I walked through just a few more pieces for your F# Adventure.  I have plenty more to cover including defining types, operators and so on that make DSLs quite useful in the .NET world.  So, subscribe if you haven't already and stay tuned.  Until next time...

kick it on DotNetKicks.com
Update:  Fixed code changed from CTP and More in the series:
After the reaction of my last post of talking about IoC and the Unity Application Block, I thought I'd include a few more samples of using Unity and how they compare with other IoC containers.  I realized after my first one, that I didn't give any love to StructureMap and I'm going to fix that for a brief sample as well.  I realize there are plenty of IoC containers out there including Spring, but quite frankly I've found it heavier than most, so I'm going to stick with Unity, Castle Windsor and StructureMap for this example.

Before I continue, check out David Hayden's screencast of IoC with ASP.NET MVC for some more interesting ideas regarding IoC and Unity.

Setter Injection versus Constructor Injection

I've been down the road of constructor injection versus setter injection.  My opinion is that you try to inject the most you can through your constructor such as in a Model View Presenter, injecting the View and the Service Layer.  Now, you may have cross-cutting concerns such as logging that you may want to swap out, but putting it in the constructor can just get ugly and you can set a default logger in your class anyways such as a NullLogger.  Martin Fowler, as always, covers this topic here and it's quite interesting as it is an open debate.

The other option I've done down this road was to create an IContext interface which is injected through the constructor that has some of the cross-cutting concerns wrapped up into it, but for now, let's just walk through a sample of having setter injection as well. 

Get Down to Details

Now that we got all the other stuff out of the way, let's go ahead and set up some basic examples in Unity, Castle Windsor and StructureMap doing setter injection.  I'll basically take the code from last time and apply it here as well.  So, let's start out with the Unity Application Block Sample:

namespace UnitySamples

{

    public interface ILogger

    {

        void Log(string message);

    }

}


And we have two implementations, the NullLogger (the default) and the ConsoleLogger (the override).  Let's go through each of those.

namespace UnitySamples

{

    public class NullLogger : ILogger

    {

        public void Log(string message)

        {

            // Do nothing

        }

    }

}


using System;

 

namespace UnitySamples

{

    public class ConsoleLogger : ILogger

    {

        public void Log(string message)

        {

            Console.WriteLine(message);

        }

    }

}


Now that I have these two implementations, I won't bother repeating these for the others unless they specifically change, which they shouldn't.  Now, to my implementation details of my CustomerTasks object.

using Microsoft.Practices.Unity;

 

namespace UnitySamples

{

    public class CustomerTasks

    {

        private ILogger logger = new NullLogger();

 

        [Dependency]

        public ILogger Logger

        {

            get { return logger; }

            set { logger = value; }

        }

 

        public void SaveCustomer()

        {

            Logger.Log("Saved customer");

        }

    }

}


As you may note, I set the default implementation of my logger to a NullLogger because by default, I don't care about logging, so it's about the same as a NoOp.  But, if I want to change that, I can through my setter injection.  This goes for any cross-cutting concern.  I also marked my Logger property with the DependencyAttribute which basically says that give me the ILogger instance registered when you go through the container to create it.  This of course requires class modification, so it's not a simple rip and replace as it was with constructor injection.  So, now let's look at the implementation of our configuration, much as before.

using System.Configuration;

using Microsoft.Practices.Unity;

using Microsoft.Practices.Unity.Configuration;

 

namespace UnitySamples

{

    class Program

    {

        static void Main(string[] args)

        {

            IUnityContainer container = new UnityContainer();

            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            section.Containers.Default.GetConfigCommand().Configure(container);

            CustomerTasks tasks1 = container.Resolve<CustomerTasks>();

            CustomerTasks tasks2 = container.Resolve<CustomerTasks>();

            tasks1.SaveCustomer();

            tasks2.SaveCustomer();  

        }

    }

}


And the configuration file will look much like before as:

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

<configuration>

  <configSections>

    <section name="unity"

            type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,

                  Microsoft.Practices.Unity.Configuration" />

  </configSections>

  <unity>

    <containers>

      <container>

        <types>

          <type type="UnitySamples.ILogger,UnitySamples"

                mapTo="UnitySamples.ConsoleLogger,UnitySamples"

                lifetime="Singleton"/>

        </types>

      </container>

    </containers>

  </unity>

</configuration>


Now, let's do the same thing with Castle Windsor.  Most of the code will be the same from our Unity sample as I can't imagine that much will change except that I don't need to register the DependencyAttribute on the CustomerTasks object.  Let's first look at the changed CustomerTasks object.

namespace CastleSamples

{

    public class CustomerTasks

    {

        private ILogger logger = new NullLogger();

 

        public ILogger Logger

        {

            get { return logger; }

            set { logger = value; }

        }

 

        public void SaveCustomer()

        {

            Logger.Log("Saved customer");

        }

    }

}


Now, let's look at the program.cs file to see how really nothing changed at all from our perspective:

using Castle.Windsor;

using Castle.Windsor.Configuration.Interpreters;

 

namespace CastleSamples

{

    class Program

    {

        static void Main(string[] args)

        {

            WindsorContainer container = new WindsorContainer(new XmlInterpreter());

            CustomerTasks tasks1 = container.Resolve<CustomerTasks>();

            CustomerTasks tasks2 = container.Resolve<CustomerTasks>();

            tasks1.SaveCustomer();

            tasks2.SaveCustomer();

        }

    }

}


And then our config file looks like this:

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

<configuration>

  <configSections>

    <section name="castle"

        type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />

  </configSections>

  <castle>

    <components>

      <component id="customertasks" type="CastleSamples.CustomerTasks, CastleSamples" lifestyle="transient" />

      <component id="logger.console" service="CastleSamples.ILogger, CastleSamples" type="CastleSamples.ConsoleLogger, CastleSamples" lifestyle="singleton" />

    </components>

  </castle>

</configuration>


So, in reality, nothing changed from our constructor injection versus our setter injection implementation for Castle Windsor.  That to me is pretty cool...  But, now, let's move our attention to StructureMap.  Let's walk through only the code that has changed.  I'm only going to use the one with the StructureMap.config file and not the fluent interfaces just yet.  I know more of the config file and not enough of the interfaces to be effective.  Let's go through what really changed.  In reality, everything is the same from the Castle Windsor implementation and the StructureMap one except for the Program.cs and the StructureMap.config file, so let's look at the Program.cs first.

using StructureMap;

 

namespace StructureMapSamples

{

    class Program

    {

        static void Main(string[] args)

        {

            CustomerTasks tasks1 = ObjectFactory.GetInstance<CustomerTasks>();

            CustomerTasks tasks2 = ObjectFactory.GetInstance<CustomerTasks>();

            tasks1.SaveCustomer();

            tasks2.SaveCustomer();  

        }

    }

}


And to make sure our object is a singleton, let's make our StructureMap.config file and walk through the details:

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

<StructureMap>

  <PluginFamily Type="StructureMapSamples.ILogger" Assembly="StructureMapSamples" DefaultKey="Console">

    <Interceptors>

      <Interceptor Type="Singleton" />

    </Interceptors>

    <Plugin Assembly="StructureMapSamples" Type="StructureMapSamples.ConsoleLogger" ConcreteKey="Console" />

    </PluginFamily>

  <PluginFamily Type="StructureMapSamples.CustomerTasks" Assembly="StructureMapSamples" DefaultKey="CustomerTasks">

    <Plugin Assembly="StructureMapSamples" Type="StructureMapSamples.CustomerTasks" ConcreteKey="CustomerTasks">

      <Setter Name="Logger" Key="Console" />

    </Plugin>

  </PluginFamily>

</StructureMap>


If you're familiar with StructureMap, the config file should make sense to you as I'm creating an ILogger with the default implementation being the ConsoleLogger and then we make sure it is a singleton through the use of an interceptor.  Then we also do a setter injection through our plugin of the CustomerTasks with setting the Logger property to the key of Console.  Pretty simple and straightforward.

So, as you can see, they are very similar in nature, but attack the problem in different ways.  That's the beauty of it all, just determine your needs and your programming style and then the pick of your IoC container should come into line with that.  These are pretty simple and naive samples, but I just want to whet your appetite to open your mind and look for yourself at these containers for yourself.

AOP with PostSharp and Unity?

Gael Fraiteur recently posted on the altdotnet list about the new release of PostSharp.  Gael blogged about that here.  A couple of things intrigued me about it, including the license change to LGPL for the runtime and GPL for the code.  This requires a commercial license should you want to redistribute it with your application.  But, I'll leave that up to him and the lawyers to figure out. 

But, let's get back to Unity for just a second.  Gael recently announced on the Unity Application Block discussion list about including an extension to support PostSharp which you can find here.  You can find the code in particular to do this, plus the Stoplight sample converted at GoogleCode here under PostSharp4Unity.  Get your favorite SVN client and pull it down.

So, let's take my basic example from above and try to get it using the default constructors instead of the approach of calling the container to get ourselves an instance.  A good approach is to keep the container out of your way and produce cleaner code.  A downside of using IoC containers is that they can litter up your code.  PostSharp4Unity allows us to create an extension for Unity and use our default constructors.

First, let's create a Unity container provider so that we can initialize our container programmatically.  Create a UnityContainerProvider in your project that inherits from the IUnityContainerProvider.  That code should look like this:

using Microsoft.Practices.Unity;

using PostSharp4Unity;

using UnitySamples;

 

namespace UnitySamples

{

    public sealed class UnityContainerProvider : IUnityContainerProvider

    {

        private readonly IUnityContainer container;

 

        public UnityContainerProvider()

        {

            this.container = new UnityContainer()

                .RegisterType<ILogger, ConsoleLogger>(new ContainerControlledLifetimeManager());

        }

 

        public IUnityContainer CurrentContainer

        {

            get { return this.container; }

        }

    }

}


Now we also have to mark our assemblyinfo.cs with our default UnityProviderContainer, so open up your assemblyinfo.cs and put this info in there:

using PostSharp4Unity;

using UnitySamples;

 

[assembly: DefaultUnityContainerProvider(typeof(UnityContainerProvider))]


Ok, done and now we have to mark our class that we want to mark our configurable objects that we want to control with PostSharp.  So, open CustomerTasks and modify it to this:

using Microsoft.Practices.Unity;

using PostSharp4Unity;

 

namespace UnitySamples

{

    [Configurable]

    public class CustomerTasks

    {

        private ILogger logger = new NullLogger();

 

        [Dependency]

        public ILogger Logger

        {

            get { return logger; }

            set { logger = value; }

        }

 

        public void SaveCustomer()

        {

            Logger.Log("Saved customer");

        }

    }

}


So, then our program.cs can look like this now:

namespace UnitySamples

{

    class Program

    {

        static void Main(string[] args)

        {

            CustomerTasks tasks1 = new CustomerTasks();

            CustomerTasks tasks2 = new CustomerTasks();

            tasks1.SaveCustomer();

            tasks2.SaveCustomer();  

        }

    }

}


But, in order for PostSharp to do its magic, we need to make sure it's part of our compilation targets in our .csproj file.  So, I hand munged mine and got it to work like this:

  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(PostSharpDirectory)PostSharp.targets" Condition=" Exists('$(PostSharpDirectory)PostSharp.targets') " />
</Project>

Then I'm able to get the magic of PostSharp to do its work.  Pretty slick!

Wrapping It Up

So, I hopefully whetted your appetite for these IoC containers for you to go and do a comparison on your own.  Each container has a different way of configuring itself and each solves a different problem set.  It's up to you to decide which one to use.  Along the way you can have a pretty cool journey though in learning deciding what works for you and what doesn't.  Until next time, and hopefully an F# related post...

kick it on DotNetKicks.com
At the last DC ALT.NET meeting, there was a good discussion regarding premature optimization.  Anything that involves this brings me to a rather famous quote by a great computer scientist, Donald Knuth which states:

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

Don't Think Five Steps Ahead
 
The context of the conversation revolved around how when you learn a new language, you have a tendency to think inside the box and try not to prematurely optimize the code, instead, just meet the original intent of what you were trying to do as quickly and efficiently as possible and make it conform to the specification.  For example, one person there was a .NET guy who knew nothing of Java until put on a project recently where it was exclusively used.  This forced him to think more clearly about the problem and not just throw design patterns, caching solutions and so on.  When we are familiar with a language and all of its nuances, it sometimes gets the better of us, and we start throwing frameworks in there that have done things for us in the past just because they seemed appropriate then. It rang very true for me as well when I did my first Ruby on Rails application and I saw that I didn't need to bring in X framework or Y framework and my solution did just fine without it.  In fact, I thought it was a stronger piece because I didn't clutter it with frameworks and instead solved the direct domain problem at hand first.

It kind of reminds me of a conversation I once had with a developer which went like this:

Me: Why did you use x for this piece?
Him:  Because it's always worked for me in the past.
Me:  What problem does it solve?  Did you have that problem this time around?
Him:  Well, no, I was just thinking five steps ahead

So, basically what we can infer from this conversation is that the pain point just hadn't been hit yet.  Instead, reflexively, we have a tendency to throw these things in there because at one point, for one particular project, we felt that pain.  That's not to say that optimization is a bad thing, but once we start doing it, we need concrete measures for what the optimization is trying to fix and how well it does it.  Another part to consider is how easy is it to read.

ADD with DDD

Some of the guidance for this can be traced back to Domain Driven Design.  With this, you pay more attention to the model, the ubiquitous language and so on, and the frameworks in turn will come into play.  Instead, many people put their frameworks first and try to get the domain model to fit around it.  They are distracted by shiny things with their ADD to put the domain model first and then the frameworks.  I know I've been guilty of it in the past and it's been a learning adventure when I was earlier in my career.

I'll be back next with a real technology post on IoC, Unity and all that, so stay tuned.  Until next time...

kick it on DotNetKicks.com
Update:  Fixed code changed from CTP and More in the series:

I thought after my recent F# post, I'd get back to the Unity post that was halfway done before the firestorm began...

In a previous post, I showed how easy it was to create a basic application using the Unity Application Block. I'm always finding new ways to solve my problems and new tools to do it.  Since Inversion of Control (IoC) containers are near and dear to my heart, I thought I'd investigate to see whether it meets my needs or not.  It's something you need to determine on your own, whether it works for you.  Some like Spring.NET, others StructureMap, Castle Windsor and so on.

Purse Fight???

Now, there has been some rather heated discussion around the Unity Application Block on the altdotnet mailing list.  The discussion even got heated enough for the ALT.NET Pursefight blog to come back into action after a long hibernation with a post called "Dear Idiots"...

Compare/Contrast with Windsor

Anyhow, today I will focus on a little compare/contrast with Castle Windsor just to show the different styles used.  I'm not going to say one is better than the other, because quite frankly, that's up to you to decide...  I want to thank Dustin Campbell for his help in getting a better code formatter via this post here.

So, let's just take a sample from before and have our ILogger and create a singleton first using the Unity Container.  So, we will go ahead and use the ILogger interface, and create a concrete implementation of that called ConsoleLogger, inject it into the constructor and then call the Log method from within the CustomerTasks class.  Pretty simple scenario especially when dealing with cross cutting concerns.  So, the code to do this is below.

namespace UnitySamples

{

    public interface ILogger

    {

        void Log(string message);

    }

}


Now that we have a simple, undecorated interface, let's actually implement it in code for a simple console logger.  Not practical for real use, but shows a point.

using System;

 

namespace UnitySamples

{

    public class ConsoleLogger : ILogger

    {

        public ConsoleLogger()

        {

            Console.WriteLine("Hello from constructor");

        }

 

        public void Log(string message)

        {

            Console.WriteLine(message);

        }

    }

}


Now that we have that, let's create a class that takes an ILogger through constructor injection.

namespace UnitySamples

{

    public class CustomerTasks

    {

        private readonly ILogger logger;

 

        public CustomerTasks(ILogger logger)

        {

            this.logger = logger;

        }

        public void SaveCustomer()

        {

            logger.Log("Saved customer");

        }

    }

}


Ok, time to actually start up the UnityContainer by registering everything through code.  It's a pretty simple operation.  We want the ILogger instance to be a singleton instance.  This happens during the registration process by calling the SetSingleton<T>() method off the container itself.  Note the nice fluent interfaces for doing this component registration.

using Microsoft.Practices.Unity;

 

namespace UnitySamples

{

    class Program

    {

        static void Main(string[] args)

        {

            UnityContainer container = new UnityContainer();

            container.RegisterType<ILogger, ConsoleLogger>(new ContainerControlledLifetimeManager());

            CustomerTasks tasks1 = container.Resolve<CustomerTasks>();

            CustomerTasks tasks2 = container.Resolve<CustomerTasks>();

            tasks1.SaveCustomer();

            tasks2.SaveCustomer();       

        }

    }

}


So, as you can see, no real config file was really necessary for me to do any of this.  It was a simple registration process of creating a UnityContainer.  But, that's not ideal, so let's set it as a singleton using the config file instead:

using System.Configuration;

using Microsoft.Practices.Unity;

using Microsoft.Practices.Unity.Configuration;

 

namespace UnitySamples

{

    class Program

    {

        static void Main(string[] args)

        {

            IUnityContainer container = new UnityContainer();

            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            section.Containers.Default.GetConfigCommand().Configure(container);

            CustomerTasks tasks1 = container.Resolve<CustomerTasks>();

            CustomerTasks tasks2 = container.Resolve<CustomerTasks>();

            tasks1.SaveCustomer();

            tasks2.SaveCustomer();       

        }

    }

}


You'll notice that the configuration is still kind of awkward for having to get the configuration section this way and I'm hoping for a cleaner registration soon enough.  And the configuration file would look like this for the registration.  Note that I'm setting the lifetime to Singleton.  For those familiar with Castle Windsor, it should look pretty familiar.

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

<configuration>

  <configSections>

    <section name="unity"

            type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,

                  Microsoft.Practices.Unity.Configuration" />

  </configSections>

  <unity>

    <containers>

      <container>

        <types>

          <type type="UnitySamples.ILogger,UnitySamples"