Search
Me

Developer for Forward. Former Technical Lead at ThoughtWorks.

Recent Comments
Elsewhere

Entries in c# (3)

Wednesday
07May2008

Ruby Influenced C#

Before joining my current project I spent about 4 months working with Ruby every day, the first time I’d done so for a few years. It was a glorious time: uncluttered syntax, closures, internal iterators, and with open classes, the ability to extend the ‘core’ at will.

Today I’m working with C# and .NET, and I’ve noticed that those 4 months with Ruby have changed the way I’ve been writing code. Most noticeably, I’m using anonymous delegates a lot more. But that’s not all.

I’ve found myself aching to use the List<T>’s ForEach method; I’m now wired to use Ruby’s internal iterators where instead of

List people = FindAllPeople();
foreach (Person person in people) {
   ...
}

I can instead do

List<Person> people = FindAllPeople();
people.ForEach(delegate(Person person) {
  Console.WriteLine(person.Name);
});

But, frequently I’m put off by the surrounding guff that’s needed to express the same and have almost always gone back to the more traditional external iterator-based approach. It’s simply too high-a-price to pay.

One of the largest smells I’ve noticed recently (to my mind) appears driven out of not having open classes and external iterators. If they were there, I’m sure people would use them. The result: all across the codebase, whenever you need to convert from type to another you’ll see

List<Person> people = FindAllPeople();
List<String> firstNames = new List<String>();

foreach (Person person in people) {
  firstNames.Add(person.Name);
}

This smells to me. But it really, really smells from having used Ruby where I would previously have written something as succinctly as this:

find_all_people.collect {|person| person.name}

(I’m sure other languages could do equally good things- but I’m familiar with Ruby, before the Pythonists pounce :p)

Well, turns out that you can get nearly there with C# 2.0 and .NET 2.0 with the almost certainly underused ConvertAll method (also part of List<T>).

List<Person> people = FindAllPeople();
List<String> names = people.ConvertAll(delegate(Person person) {
  return person.Name;
});

There’s still a fair bit of accidental complexity remaining- lot’s of delegate and type declarations.

C# 3.0 introduced lambda expressions and we can use that to bubble our soup down to a nice intentional broth even more. We can get rid of the delegate bumpf and let the compiler infer the type (we are still statically typed after all)

List<Person> people = FindAllPeople();
List<String> names = people.ConvertAll(person => person.Name);

Next step, we can also infer the types for our local variables:

var people = FindAllPeople();
var names = people.ConvertAll(person => person.Name);

Pretty nice. Most of the code is focused on the task at hand, and on expressing the necessary complexity (what it means to convert people to names). Guess learning a new language each year has it’s benefits.

I’ve got another bit of Ruby influenced C# refactoring to cover (a somewhat declarative way of removing switch statements), hopefully I’ll get that posted tomorrow!

Monday
07Apr2008

Poor Man's C# Singleton Checker

Paul Hammant wrote a nice article about how to refactor the “nest-of-singletons design” towards using dependency injection using Google’s Guice IoC Container.

Whilst waiting for one of my many builds to finish today, I figured I’d satisfy a curiosity - roughly how many singletons are there defined within this codebase. I fired up Cygwin and used the following

find . -type f -name “*.cs” | xargs cat | grep “public static [A-Za-z]\{1,100\} Instance” | wc -l

Result:

180

Yikes!

For Java, you can always use the Google Singleton Checker which also has some nice stuff about why they’re controversial.

(Update) Paul Hammant pointed out that his article wasn’t about refactoring out singletons, rather, breaking away from using the service locator to dependency injection. Apologies for muddling it up a little :)

Monday
16Jul2007

C# Anonymous Delegates, MVP, and testing with NUnitForms

I’m not sure why, but I get the feeling that anonymous delegates in C# 2.0 haven’t really had much of a press and people aren’t really that aware of them.

Essentially, it lets you declare the delegate inline a la:

public delegate void MyDelegate();
...
private void DoIt(MyDelegate codeBlock)
{
codeBlock();
}
public void AddInstrumentToPrice(string message)
{
DoIt(delegate { Console.WriteLine(message); });
}

Closures!

On my current project we’ve found some great use for them, in particular, once we’d started refactoring some GUI code into the Model-View-Presenter pattern as described in Michael Feathers’ Humble Dialog paper (pdf). This tidied a lot of the code up nicely, keeping the GUI code focused, allowing us to then focus a little more on improving the behaviour of the UI.

The Windows Forms UI needed to show a progress bar indicating how far it was through pricing all of the selected trades. But, with our pricing occurring within the same thread our UI was locking. So, you push the processing out into a worker thread and then you can update both, right? Wrong, because .NET will throw an exception should you attempt do this - because Windows itself doesn’t like it when you do.

The Control class includes an Invoke method that executes a Delegate on the UI thread. So, to ensure our UI updates execute on the UI thread we can write the following

public void calculateButton_click (object m, mouseeventargs e) {
this.Invoke(delegate { resultsList.Items.Add("a result!") });
}

Testing With NUnitForms

Once we had that written, we had an additional problem - we now had code executing on different threads making it difficult to test through the GUI. Sure, we had a lot of tests that drove out the implementation of the Presenter, but, it’s always nice to know that the GUI is behaving, and you’re driving something end to end.

Our solution — use the Strategy pattern to extract out the behaviour around how code is executed in the GUI, we use an anonymous method/delegate to pass a code block to a class that either executes it on the same thread (for our tests), or, uses ThreadPool.QueueUserWorkItem.

So our end-to-end NUnitForms test might look something like

[SetUp]
public void Initialisation() {
form = new SampleForm(new SameThreadWorker());
}

class SameThreadWorker : IWorker {
public void Do(WaitCallback block) {
block(null);
}
}

[Test]
public void ShouldShowResultInListAfterCalculating() {
ClickButton("calculateResults");
Assert.IsTrue(ListContains("resultsList", "My Result"))
}

Which is handled inside the form by

public void calculateButton_click (object m, mouseeventargs e) {
worker.Do(delegate { resultsList.Items.Add("a result!") });
}

And our default worker for the GUI? Something a little like

class UserWorkItemWorker : IWorker {
public void Do(WaitCallback block) {
ThreadPool.QueueUserWorkItem(block);
}
}

Probably not the best way of doing it, but certainly better than most I could think of, and all thanks to anonymous delegates.