markhneedham/blog huggingface dataset:
Coding: Putting code where people can find it
Date: 2009-06-02 23:35:31

I've previously written about the http://www.markhneedham.com/blog/2009/01/21/c-builder-pattern-still-useful-for-test-data/[builder pattern] which I think is a very useful pattern for helping to setup data.

It allows us to setup custom data when we care about a specific piece of data in a test or just use default values if we're not bothered about a piece of data but need it to be present for our test to execute successfully.

One problem that I noticed was that despite the fact we had builders for quite a number of the classes we were using in our tests, when new tests were being added test data was still being setup by directly using the classes instead of making use of the builders which had already done the hard work for you.

A colleague and I were pairing last week and I pointed out one of these areas and he suggested that we should try and introduce the builder pattern to try and solve it!

We actually didn't have a builder for that particular piece of data yet but I pointed out several other builders we did have which he wasn't aware actually existed.

Clearly I hadn't done a very good job of communicating the existence of the builders but when discussing this we realised that the turn around time for checking whether or not a builder existed was actually not very quick at all.

* Start writing test and realise that test data setup was a bit complicated
* At best search for 'ClassNameBuilder' if you knew that was the naming convention for these builders
* Create test data for the test by typing 'new ClassNameBuilder()\...'

We therefore came up with the idea of anchoring the builders to a common class which we called 'GetBuilderFor'.

It is now possible to create test data by writing code like this:

[source,csharp]
----

var car = GetBuilderFor.Car().Year("2009").Make("Audi").Build();
----

The nice thing about this is that we now only have to type in 'GetBuilderFor' and then a '.' and ReSharper will show us all the builders that are available to us. If there isn't one then we can create it.

Communication wise we've both been mentioning this approach in our stand ups and to other people when we pair with them and hopefully this approach will stop the duplication of test data creation.

For those in the Java world http://blog.jayfields.com/2009/01/most-java-unit-tests-consist-of-class.html[Jay Fields wrote a cool post a few months ago where he describes a way to do a similar thing in Java]. I think this is one place where having static imports makes the code read really fluently.
F#: Setting properties like named parameters
Date: 2009-06-29 00:28:14

One of the most frustrating things for me lately about interacting with C# libraries from F# has been setting up objects through the use of properties.

While I am against the use of setters to construct objects in the first place, that's the way that a lot of libraries work so it's a bit of a necessary evil!

In C# we would typically make use of the http://www.markhneedham.com/blog/2009/02/16/c-object-initializer-and-the-horse-shoe/[object initializer] syntax to do this, but in F# I've been writing code like this to do the same thing:

[source,ocaml]
----

type MessageBuilder(?message:string, ?user:string) =
	let buildMessage message user =
	   let twitterStatusBuilder = new TwitterStatus()
	      twitterStatusBuilder.Text <- message
	      twitterStatusBuilder.User <-
	      	let userBuilder = new TwitterUser()
	         userBuilder.ScreenName <- user
	         userBuilder
	      twitterStatusBuilder

	member self.Build() =
		buildMessage (if message.IsSome then message.Value else "") (if user.IsSome then user.Value else "")
----

This is more verbose than strictly necessary but I wanted to try and ensure all mutations to objects were being done within the function creating it rather than creating an object and then mutating it which feels strange to me in F# land.

I recently realised that it's actually possible to call properties http://msdn.microsoft.com/en-us/library/dd233192(VS.100).aspx[in the same way that we can create objects using named parameters].

We therefore end up with the following code:

[source,ocaml]
----

type MessageBuilder(?message:string, ?user:string) =
    let buildMessage message user = new TwitterStatus(Text = message, User = new TwitterUser(ScreenName = user))

    member self.Build() =
        buildMessage (if message.IsSome then message.Value else "") (if user.IsSome then user.Value else "")
----

Which is much more concise and does the same thing.
Functional Collection Parameters: Handling the null collection
Date: 2009-06-16 20:29:29

One of the interesting cases where I've noticed we tend to avoid http://www.markhneedham.com/blog/2008/12/17/functional-collection-parameters-in-c/[functional] http://www.markhneedham.com/blog/2009/01/19/f-vs-c-vs-java-functional-collection-parameters/[collection parameters] in our code base is when there's the possibility of the collection being null.

The code is on the boundary of our application's interaction with another service so it is actually a valid scenario that we could receive a null collection.

When using extension methods, although we wouldn't get a null pointer exception by calling one on a null collection, we would get a 'source is null' exception when the expression is evaluated so we need to protect ourself against this.

As a result of defending against this scenario we have quite a lot of code that looks like this:

[source,csharp]
----

public IEnumerable<Foo> MapFooMessages(IEnumerable<FooMessage> fooMessages)
{
	var result = new List<Foo>();
	if(fooMessagaes != null)
	{
		foreach(var fooMessage in fooMessages)
		{
			result.Add(new Foo(fooMessage));
		}
	}
	return result;
}
----

The method that we want to apply here is 'Select' and even though we can't just apply that directly to the collection we can still make use of it.

[source,csharp]
----

private IEnumerable<Foo> MapFooMessages(IEnumerable<FooMessage> fooMessages)
{
	if(fooMessages == null) return new List<Foo>();
	return fooMessages.Select(eachFooMessage => new Foo(eachFooMessage));
}
----

There's still duplication doing it this way though so I pulled it up into a 'SafeSelect' extension method:

[source,csharp]
----

public static class ICollectionExtensions
{
       public static IEnumerable<TResult> SafeSelect<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
       {
               return source == null ? new List<TResult>() : source.Select(selector) ;
       }
}
----

We can then make use of this extension method like so:

[source,csharp]
----

private IEnumerable<Foo> MapFooMessages(IEnumerable<FooMessage> fooMessages)
{
	return fooMessages.SafeSelect(eachFooMessage => new Foo(fooMessage));
}
----

The extension method is a bit different to the original way that we did this as I'm not explicitly converting the result into a list at the end which means that it will only be evaluated when the data is actually needed.

In this particular case I don't think that decision will have a big impact but it's something interesting to keep in mind.
C#/F#: Using .NET framework classes
Date: 2009-06-16 18:55:38

I was recently discussing F# with a couple of colleagues and one thing that came up is the slightly different ways that we might choose to interact with certain .NET framework classes compared to how we use those same classes in C# code.

One of those where I see potential for different use is the Dictionary class.

In C# code when we're querying a dictionary to check that a value exists before we try to extract it we might typically do this:

[source,csharp]
----

public string GetValueBy(string key)
{
	var dictionary = new Dictionary<string, string>() { {"key", "value" } };

	if(dictionary.ContainsKey(key))
	{
		return dictionary[key];
	}	
	return ""; // maybe we'd do something else here but for the sake of this we return the empty string
}
----

There is an alternative way to do this but it makes use of the 'out' keyword so it's generally frowned upon.

[source,csharp]
----

public string GetValueBy(string key)
{
	var dictionary = new Dictionary<string, string>() {{"key", "value"}};
	string value = "";
	dictionary.TryGetValue(key, out value);
	return value;
}
----

In F# when we make use of a method which effectively defines a second return parameter by using the 'out' keyword the return value of that method becomes a tuple containing that value.

For example when querying Dictionary:

[source,ocaml]
----

open System.Collections.Generic
open System
open System.Globalization

let testDictionary =
    let builder = new Dictionary<string, string>()
    builder.Add("key1", "value")
    builder

let getByKey key =
    let result, value =  testDictionary.TryGetValue(key)
    if(result) then value result else ""
----

The return type of TryGetValue is 'bool * string' in this case and by assigning that result to two different values we can get the appropriate values. This is certainly a time when http://www.markhneedham.com/blog/2009/06/02/f-tuples-dont-seem-to-express-intent-well/[tuples] are really useful for simplifying our code.

We could have made use of an 'out' parameter as we did in C# but I think it's much easier to just use the tuple. Dustin Campbell http://diditwith.net/2008/01/29/WhyILoveFResultTuples.aspx[describes the other ways we could extract a value from a dictionary on his blog].

It's not significantly more concise code wise compared to the C# way of doing things although from a brief look at the way that the Dictionary code works in http://www.red-gate.com/products/reflector/[Reflector] theoretically we are making less calls to the underlying data structure to get the value from it.

I tried timing 100,000 accesses to a dictionary with each approach to see if the total time would be significantly different but there wasn't any noticeable difference.

There are other 'Try...' methods defined in the base class library - DateTime for example has some more - which I've never used in C# so I'd be intrigued to see whether other languages that run on the CLR will make use of these methods.
Coding Dojo #18: Groovy Bowling Game
Date: 2009-06-26 18:15:23

This week's dojo involved coding a familiar problem - the http://www.markhneedham.com/blog/2008/11/06/object-calisthenics-first-thoughts/[bowling] http://www.markhneedham.com/blog/2008/11/13/coding-dojo-2-bowling-game-object-calisthenics-continued/[game] - in a different language, Groovy.

The code we wrote is available on http://bitbucket.org/codingdojosydney/bowling-game-groovy/src/tip/src/[bitbucket].

== The Format

http://camswords.wordpress.com/[Cam], http://twitter.com/deanrcornish[Dean] and I took turns pairing with each other with the code projected onto a TV. As there were only a few of us the discussion on where we were taking the code tended to included everyone rather than just the two at the keyboard.

== What We Learnt

* I've sometimes wondered about the wisdom of running dojos in newer languages but this one worked quite well because Cam has been learning Groovy and he was able to point us in the right direction when we started writing Java-esque Groovy code. The particular syntax that I didn't know about was that you can define and put items into a list in a much simpler way than in Java: I was starting to write code like this: ~~~groovy def frames = new List+++<Frame>+++() frames.Add(frame) ~~~ Which Cam simplified down to: ~~~groovy def frames = [] frames << frame ~~~ I didn't feel that I missed the static typing you get in Java although IntelliJ wasn't quite as useful when it came to suggesting which methods you could call on a particular object. </li>
 I'm even more convinced that using various languages functional equivalent of the 'for each' loop, in this case 'eachWith' and 'eachWithIndex' is http://www.markhneedham.com/blog/2009/06/18/functional-collection-parameters-a-different-way-of-thinking-about-collections/[not the way to go] and we could see http://bitbucket.org/codingdojosydney/bowling-game-groovy/src/tip/src/BowlingGame.groovy[our code becoming very complicated] when trying to work out how to score strikes thanks to our use of it!
 I think we actually got further this time in terms of the implementation although we did slow down when it came to scoring strikes to try and work out exactly how we wanted to do it. Prior to this we had been following the idea of just getting the tests to pass and driving the design of the code that way but we at this stage it seemed foolish to keep doing that as the code would increased dramatically in complexity by doing so. The two approaches we were thinking of involved using the state pattern to determine what the current frame outcome was and then work out the cumulative score based on that by looking forward to future frames or an approach that would make use of functional collection parameters (not sure exactly which ones!) to calculate the score in a more function rather than OO way. </ul>

== For next time

* We'll probably keep going with some more Groovy as it's actually more interesting than I thought it would be. I'm also keen to do a coding dojo where we http://www.antiifcampaign.com/[never make use of the if statement].+++</Frame>+++
F#: Explicit interface implementation
Date: 2009-06-07 08:19:01

I've been writing some code to map between CouchDB documents and F# objects and something which I re-learned while doing this is the way that interfaces work in F#.

In F# when you have a class which implements an interface that class makes use of explicit interface implementation.

This means that in order to access any members of the interface that the class implements you need to specifically refer to the interface by upcasting the value using the ':>' operator.

Given the following interface and class definitions:

[source,ocaml]
----

type CouchDBDocument =
    abstract DocType : string

type UserDocument =
    { UserName:string; FirstName:string; Surname:string }
    interface CouchDBDocument with member x.DocType = "User"
----

If we had the following value:

[source,ocaml]
----

let mark = { UserName = "mneedham"; FirstName = "Mark"; Surname = "Needham" }
----

In order to access the 'DocType' member of 'mark' we would need to do the following:

[source,ocaml]
----

(mark :> CouchDBDocument).DocType
----

Coming from the world of C# I had expected that it would be possible to define a value as being of type 'CouchDBDocument' and then pass in a value of UserDocument like this:

[source,ocaml]
----

let mark : CouchDBDocument = { UserName = "mneedham"; FirstName = "Mark"; Surname = "Needham" };;
----

But that doesn't actually compile:

[source,text]
----

error FS0191: The type CouchDBDocument does not contain a field UserName
----

It is possible to do this in C# as well although the implementation would be implicit in C# unless we explicitly declare it to be explicit like so:

[source,csharp]
----

public interface CouchDBDocument
{
    string DocType { get; }
}

public class UserDocument : CouchDBDocument
{
     string CouchDBDocument.DocType
    {
        get { return "User"; }
    }
}
----

To access the 'DocType' property in this case we would need to be explicitly referring to the 'CouchDBDocument':

[source,csharp]
----

CouchDBDocument mark = new UserDocument();
Console.WriteLine(mark.DocType);
----

Mauricio Scheffer has an http://bugsquash.blogspot.com/2009/01/implementing-interfaces-in-f.html[interesting post where he talks about rewriting a piece of C# code in F#] which required him to use interfaces in F# and http://cs.hubfs.net/forums/permalink/7579/7586/ShowThread.aspx#7586[Brian McNamara explains on hubfs why explicit interface implementation can actually be quite useful].

The http://www.markhneedham.com/blog/2009/05/24/real-world-functional-programming-book-review/[Real World Functional Programming book] also has a chapter which describes interfaces in C# and F# and the way they differ very clearly.
F#: What I've learnt so far
Date: 2009-06-30 23:09:35

I did a presentation of some of the stuff that I've learnt from playing around with F# over the last six months or so at the most recent http://sydney.ozalt.net/2009/05/june-meeting-f.html[Alt.NET Sydney meeting].

I've included the slides below but there was also some interesting discussion as well.

* One of the questions asked was around how you would deal with code on a real project with regards to structuring it and ensuring that it was maintainable. I'm not actually sure what the answer is to this question as I haven't written any code in F# that's in production but there are certainly applications written n F# that are in production - the main one that I know a bit about is one which http://pandamonial.com/[Amanda Laucher] worked on http://vimeo.com/3555080[which she spoke about at the Alt.NET conference in Seattle].
* There was some discussion about dynamic v static languages - http://fragmental.tw/[Phil] spoke of not caring about what type something is rather caring about what it does. I pretty much agree with this and I think when using languages which have quite strong type inference such as F# (and more-so Haskell from what I hear) then I think we do move more towards that situation.
* http://erik.doernenburg.com[Erik] raised the point that functional languages aren't the solution for everything and I certainly feel it's niche is probably around operations with heavy data parsing/mining involved. I'm not sure I'd fancy doing an ASP.NET MVC application only in F# although I've seen some WPF code written using F# (unfortunately can't remember where) which looked reasonable so I'm not sure we should write it off just yet.

I've put the code that I walked through in the presentation on http://bitbucket.org/markhneedham/altnet-sydney-fsharp/changeset/dfcbc2acf486/[bitbucket].

http://www.slideshare.net/markhneedham/f-what-ive-learnt-so-far?type=presentation[F#: What I&#39;ve learnt so far]
Javascript: Using 'replace' to make a link clickable
Date: 2009-06-08 11:57:39

I've been doing a bit more work on my http://www.markhneedham.com/blog/2009/04/13/f-a-day-of-writing-a-little-twitter-application/[twitter application] over the weekend - this time taking the tweets that I've stored in CouchDB and displaying them on a web page.

One of the problems I had is that the text of the tweets is just plain text so if there is a link in a tweet then when I display it on a web page it isn't clickable since it isn't enclosed by the '<a href"..."></a>' tag.

Javascript has a 'replace' function which you can call to allow you to replace some characters in a string with some other characters.

What I actually wanted to do was surround some characters with the link tag but most of the examples I came across didn't explain how to do this.

Luckily I came across a http://www.webmasterworld.com/forum91/562.htm[forum post from a few years ago] which explained how to do it.

In this case then we would make use of a matching group on links to create a clickable link:

[source,javascript]
----

"Interesting post... Kanban & estimates http://tinyurl.com/p58o3r".replace(/(http:\/\/\S+)/g, "<a href='$1'>$1</a>");
----

Which results in a tweet with a nice clickable link:

[source,text]
----

"Interesting post... Kanban & estimates <a href='http://tinyurl.com/p58o3r'>http://tinyurl.com/p58o3r</a>"
----
Using Fiddler with IIS
Date: 2009-06-24 17:46:23

We've been using http://www.fiddler2.com/fiddler2/[Fiddler] to debug the requests and responses sent via web services to a service layer our application interacts with and it works pretty well when you run the application using http://en.wikipedia.org/wiki/UltiDev_Cassini_Web_Server[Cassini] but by default won't work when you run the website through IIS.

The key to this as one of my colleagues (who gives credit to http://erik.doernenburg.com[Erik]) showed me today is to ensure that IIS is running under the same user that Fiddler is running under which in our case is the 'Administrator' account.

The default user for IIS is 'Network Service' but as far as I'm aware you can't actually launch an application such as Fiddler from that account.

We therefore changed IIS to run under the 'Administrator' account on local development machines since this is where we typically use Fiddler.

To do this we need to:

* Create a new application pool by going to the 'Application Pool' menu in IIS Manager and setting the 'Identity' of the new pool to be the Administrator account.
* Change the application pool for our application to match that new application pool.
* Go to 'Computer Management > Local Users and Groups > IIS_WPG' and add the Administrator as a user of that group.

Fiddler should now capture requests/responses!

I'm not sure running IIS as the Administrator account is such a great idea although it's only on the local development environment so maybe it's a reasonable trade off for the benefits we get from being able to debug web service communication.
Visual Studio/Resharper: Changing the order of arguments
Date: 2009-06-23 19:31:37

We've recently run into some places in our tests where the expectation and actual values passed into http://nunit.org/index.php[NUnit]'s 'Assert.AreEqual' are the wrong way round, therefore meaning that the error messages we get when tests fail are somewhat confusing!

[source,csharp]
----

Assert.AreEqual(theActualValue, "the expectation");
----

We can change the arguments around using Resharper by using the key combination 'Ctrl-Alt-Shift-ArrowKey' but you can only do this one line at a time which was a bit annoying as there were about 20 to change.

I got a bit bored of doing this after a while so I thought I'd look into whether it would be possible to do this with a 'Find & Replace'.

After a bit of trial and error this is what I've ended up with:

* Select all the areas of code that you want to change and press 'Ctrl-H'
* In the find box type: ~~~text \({.*}, {\".*\"} ~~~
* And in the replace box type: ~~~text (\2, \1 ~~~

The '{}' define a matching group of which we define two in this case and then switch them around. Visual Studio's regex seems a bit different than the one I'm used to - http://msdn.microsoft.com/en-us/library/2k3te2cs(VS.80).aspx[the reference list for the syntax is available on MSDN].

It's not too complicated and I'm sure there are edge cases where it wouldn't work but for the little case I had it did the job reasonably well.