Thursday, November 5, 2009

Functional .Net : Tuple

Tuple's really don't have a lot to do with functional programming, they are a common concept in many language that for some reason are only making their way in the .Net on version 4.0. One could argue that you could have always easily constructed your own Tuple class but unnecessary duplication of such a simple type has obviously become apparent to the BCL team. This is good. Simple classes like this should be present in the framework. :)

So what is a Tuple? It is basically a container of a finite list of objects; a Point could be described as a list of 2 values Tuple<int, int> where the int values could be the X and The Y coordinates of a point. A Date could be described as Turple<int,int,int> with the values being Year, Month & Day. It is not a list in that your would typically enumerate through the items but you would reference them by index. You may be ask why is this different to an Array eg int[3]? Well with a Tuple the list length is set at compile time and the type of each index point is also set. Tuple<int,string,DateTime> forces you to always have the DateTime as the 3rd item. This is all pretty under-whelming to be honest, but like anything cool its the simplicity that is its strength and also why it pops up in functional styled programming a lot. Future demos are likely to include Tuples :)

Thursday, October 29, 2009

Functional .Net : Currying

Currying is another functional technique that is possible to achieve with C#. The technique basically allows the rewriting of a function that takes in multiple arguments to one that takes in one argument and returns a function which may in turn take more arguments, the basic premise being able to build up composite function by splitting functions down and reducing the number of parameters dealt with. I will be honest and say that  I have found the language you use (C#, F#, Haskell etc) would be more influential to your predisposition  in using this technique, as it is with many of the function patterns and IMO C# does not lend itself nearly as well as F# for example. That being said it still can be done so lets look at a basic example. For starters currying is something that is not catered for explicitly out the box in C# but can easily be done using extension methods eg:

public static Func<TArg1, Func<TArg2, TResult>> Curry<TArg1, TArg2, TResult>(this Func<TArg1, TArg2, TResult> func)
{
return a1 => a2 => func(a1, a2);
}
public static Func<TArg1, Action<TArg2>> Curry<TArg1, TArg2>(this Action<TArg1, TArg2> action)
{
return a1 => a2 => action(a1, a2);
}


These extension method now allow you to take a 2 parameter delegate and split it into a one parameter argument return an Action or Func that take one argument. This can obviously be extended and helps facilitate the separation and composition of functions.



Now from my understanding of currying it is a specific form of partial application, being that currying splits its functions down to single argument delegates while partial application make no such claim, i.e. a three argument function be be reduced to a single argument function returning a 2 argument delegate. As this is purely academia I don't really care, the principle is the same.



A trivial example of currying (I'm lazy I stole it from Matt P and it is using the extension method above) :



Func<int, int, int> multiply = (x, y) => x * y;
var curriedMultiply = multiply.Curry();
var curriedMultiplyThree = curriedMultiply(3);
var curriedMultiplyResult = curriedMultiplyThree(15);
Console.WriteLine("Result of 3 * 15 = {0}", curriedMultiplyResult);


Unfortunately the verbosity of C# when approaching this style of coding very quickly begins to put me off.  The equivalent in F# is much more readable, but hey its what the language is strong at so it really should be a nicer experience. Either way its good to know the facilities are there if one day I do ever need to use it.



Basically the take away from this post is the extension methods at the top, with out these there will be no curry love.



Links forwarding (yeah this was a lazy post):



http://codebetter.com/blogs/matthew.podwysocki/archive/2009/04/26/functional-c-forward-functional-composition.aspx



http://mikehadlow.blogspot.com/2008/03/currying-in-c-with-oliver-sturm.html



http://stackoverflow.com/questions/411572/proper-currying-in-c

Tuesday, October 13, 2009

Functional .Net : Closures

One of the more commonly used functional techniques that can be used in C# is the use of Closures, a technique that if your are currently using lambdas, you may be using them inadvertently. My understanding of closure may be different to others as there seems to be so many subtlety different definitions especially when comparing languages. Anyway, in my mind the comments of Javascript closure best align with my understanding (http://www.jibbering.com/faq/faq_notes/closures.html)

A closure is a delegate that has references to a variable not passed to it and in an scope outside the delegates immediate scope.

Like any delegate its definition and execution are not the same thing. You can define a closure and never use it or just call it later

A simple closure example I can think of is:

static void Main(string[] args)
{
var timesToRepeat = 100;
//Declare the Action
Action<string> print = text => //text (string) is the only parameter
{
//using varb declared outside of Action
for (int i = 0; i < timesToRepeat; i++)
{
Console.WriteLine(text);
}
};
timesToRepeat = 3;//Lets modify the variable
print("Hello!");//Call the action/evaluate the expression
//Prints:
//Hello!
//Hello!
//Hello!
}


Note that the timeToRepeat variable is declared outside of the declaration of the lambda statement. Think about this; the Action 'print' can be passed out side of this scope, it could be passed to another class which does not have visibility of the locally declared variable. The 'print' expression is bound to that variable declared outside of its scope. This obviously has ramification in terms of holding reference to that object. Please also note that the expression 'print', like all delegates is evaluated when it is called, not when it is declared; Stepping over the above code will not print when declaring the 'print' Action but at the last line when it is called. One last thing to note is that the variable timetoRepeat is modified after defining the print Action and this is carried when we call 'print' in the last line; "Hello!" is printed 3 times, not 100 times as the variable would imply when the closure was declared.



You may have been using closures with out knowing it. Javascript and the associated libraries like jQuery use this technique a lot, as do many open source library such as TopShelf, MassTransit etc.

Monday, October 12, 2009

Functional .Net : First Class Functions

One thing I notice in .Net is that many developers do not think of functions as first class citizens. I guess in the OO world classes or more appropriate the instance representations are the real hero's, however, in my mind, functions deserve much more appreciation than they perhaps get.

Since .Net 1.0 delegates have been around and I still think many developers do not fully understand how they work. I have previously made a post with regard to delegates showing how they can be used in a real world way to save code duplication here. I guess one of the first steps to being comfortable with functional programming is being comfortable with functions as first class citizens; The best way for a typical C# developer to do this is get comfortable with delegates. Before I continue on with my Functional programming journey I want others following with me to be on the same page. Please be sure you understand what a method & delegate are; I feel I describe them reasonably well on the previous mentioned post.

Functional .Net: The Beginning

Of late I have (along with a few colleagues and friends) started to make a bit more of a concerted effort to up skill in the area of functional programming. I admit that my knowledge is  of functional programming is high level (at best) although have in advertently been using several of the core concepts due to the language feature I am exposed by the C# language I use on a day to day basis.

What has spurred me on is the talks from Dr Erik Miejer on channel 9 (the first of 13 can be found here). The talks plan on tackling Functional programming by working through the benchmark Functional book: Programming in Haskell

I am keen to see how the series progresses, I am only up to episode 2 but am already seeing value, more in the "why" as opposed to the "how", which is fine for this early stage of my journey.

I also want a bit of commercial return on investment with relation to what I can do in my day to day job with functional programming. As I have mentioned C# actually handles several of the Functional paradigms (although perhaps not as elegantly as F# and the like) and thanks to .Net resident Functional voice-to-the-masses, a bunch of Functional programming samples in C# can be found here to download; Cheers Matt! Along with just raw C# code he has a bunch of Wiki links to highlight what each example is actually doing; you may be surprised that you are inadvertently using some of these techniques!

Any way I will keep you posted as to how I progress as I move forward on the beginning on what is hopefully a fruitful journey!

Thursday, September 24, 2009

TDD Mind Shift

Ok so I am not the fastest adopter, however recent situations have almost forced me into a new way of thinking. Recently I was going over a fellow colleagues code and was about to add a test to one of his existing fixtures. He had previously mentioned that he felt there were a lot of tests, I told him not to worry, often when you are new to TDD it seems like a lot of extra code... I had underestimated his comments, he was right there was a ton of tests, thousands upon thousands of lines of tests, in one fixture.  I had clearly not been doing my job and should have been helping him out.

The test were broken down into one fixture per class under test, using regions to separate out test groupings, typically for each method under test. There was some very basic common set up however there was still a lot of set up in each test. It became quite clear that there were certain common set ups that were occurring.  Although the test per class is common it is usually not the best way of keeping your tests together, especially if you are being thorough in your testing. What my refactoring produced was akin to something I have been following for awhile but not really embraced, context based tests.  The tests were broken up so those with common set ups were grouped in their own fixtures; i.e. those with the same defined stubs. Although in this case it was done to make maintenance easier it highlighted for me the benefits of this approach.

Fixtures become specific to the context in which they apply, not blindly and solely to the class they are testing. This will lead to lead to multiple test fixtures per class and multiple test fixtures per method. This is what initially turned me off the approach; fixtures would be come to fine grained, however I have changed tact. Although it may not always be appropriate I can see it being beneficial for many situations. For example you may emulate the Repository having no records in it (via a stubbed method call) and run a bunch of test with that context. This encourages you to test not just method calls but to think it terms of a given scenario, something that I see unit sometimes missing in the pursuit of just achieving code coverage. The fixture tend to have test that are very small and very clear as to what they are asserting, often only a couple of lines per test.

Another thing that originally put me off the notion of Context specification and BDD was the perception of tooling... RSpec etc are not required, it is the thought patterns that I think are more important. Setting up a specification can be done using basic setup method with each fixture defining a specific context. Test inheritance can be very helpful here too.

Although Context specification and BDD are not the same thing I believe they are a movement in  the same direction; moving away for blind testing to defining scenarios that we need to test. Test become closer to one of the goals of being "readable documentation".

If you do what to read up a bit more check out:

Article introducing BDD styled tests with the notion of Context Specifications : http://www.code-magazine.com/article.aspx?quickid=0805061&page=1

A nice coding example showing one way of thinking in a context spec way: http://www.lostechies.com/blogs/rssvihla/archive/2009/05/21/context-spec-style-testing-and-my-approach-to-bdd.aspx

MSpec with Boo looks to be very cool too: (requires git client): http://github.com/olsonjeffery/machine.specifications.boo

Although the shift for me has not been great it has been significant, I would encourage you to at least investigate to consider if some of the principles can be applied in your testing.

Tuesday, September 15, 2009

When Easier is Better

Most of the people I currently or have worked with know that I have a strong preference for NHibernate for my persistence mechanism. I typically use a repository pattern, often with services hiding the repositories from the outside world. This is great as I get enterprise scalable domain-driven solutions up and running pretty quick and helps me focus on fixing business problem, not spinning my wheels with infrastructure details. However some time having DTO's, services, repositories, mapping files, anti-corruption/translation layers etc are just overkill. This is where is would typically say "Use Linq2Sql", if someone asked me what they should use, but its probably not what I would use. I like the idea of having the flexibility of moving from a simple domain to a complex domain with out too much problem. Enter Castle Active Record

Active record is in no way a new concept (PEAA p160) but is heavily under used in the .Net realm. AR is a great pattern when you are fleshing out a domain. You can very quickly start building up relationships have screens up and running for client very quickly. This is great for spikes but also for writing real code. The database can be generated from the code (Castle AR sits on top of NHibernate) so it is a great fix for fast moving agile project, especially in the initial sprints. The thing I like most about it is that if I decide I want a more complex domain, all is not lost; I remove the Castle attributes and references wrap a repository pattern around it and I am done. It really is that easy. All my existing domain unit tests should still pass. In a matter of hours you could switch from a developed 2 tier app to an enterprise ready scalable architecture.

Basically AR is great if you are lazy (or need results now).

To prove all of this I plan on presenting Castle AR in an up coming Perth Alt.Net meeting. Originally I had wanted to show NHibernate however I think the progression from AR to NH will help show both of there benefits. This may also allow us to show the limits of both... time will tell.

As a side note the castle stack (as well as NHibernate) has had a "proper" release this year so if you haven't had a look in a while check it out : http://www.castleproject.org/castle/download.html

Links - Articles

http://www.castleproject.org/ActiveRecord/gettingstarted/index.html

All you wanted to know about Castle ActiveRecord - Part I

All you wanted to know about Castle ActiveRecord - Part II

Links - Videos

Ayende Rahien - Using Active Record to write less code (Oredev 2008) << Watch me I'm great!

Ayende & Hammet - Painless Persistence with Castle ActiveRecord (JAOO)