C# News From The Future: What If?
It’s a fresh September morning and I can’t quite believe it’s actually available – we’ve got a preview release of C# 6. Ever since the announcement at PDC2012 last month, I’ve been waiting to play around with a particular new feature. I remember it being a fairly average PDC until Anders shocked everyone with it – method group assignment.
Initially, I wondered what exactly it meant until someone on Twitter clarified it.

Monkey patching! It surprised me because, until now, I saw the future of C# as an increasing story of ceremony. In recent months F# has been gaining an unbelievable amount of attention because of its awesome inference and perceived simplicity due to lack of ceremony. And let’s not even mention Ruby.
Lots of the dynamic languages, in fact, seem to involve much less work these days when it comes to bending the language into a shape that fits the problem well. And really, that’s what we do as programmers. The question is: how can the language be so flexible that it lets us solve any problem?
Without Monkey Patching
I’ve been writing a really simple app that lets users register for an account and store notes. Until today, I had been jumping through hoops trying to aim for the right amount of SRP and DI that makes this thing testable. What I ended up doing was extracting an interface for each dependency of the unit that I needed to test, so that I could test it in complete isolation.
We know that interfaces weren’t intended solely for producing seams for testing, but that’s pretty much how we all use them anyway. We end up with two, three, maybe four additional interfaces and associated classes, and a dependency chain, when all we really wanted was to test the damn thing.
It’s true that we potentially get a better design in terms of looser coupling and separation of concerns, but get this: I don’t want that in this case. This is a single controller app with a small and perfectly understandable behaviour. I should be able to bend C# (and not have to work around it) into testing my app.
Ultimately we end up trading complexity for testability. Incidentally, isn’t complexity proportional to number of bugs? In reality, testability should be easy and should be part of the pit of success.
C# Just Took Up Yoga
Well, things just changed. From what I understand, the CLR guys managed to implement new functionality that allows the assignment of a delegate to a method group. It does some kind of smart matching with the delegate parameters. I don’t know all the technical details, but I do know that it freaking rocks.
Consider my simple app:
public class UserService
{
public void Register(string username)
{
using (var context = new DataContext())
{
context.Users.Add(new User
{
Username = username,
Created = DateTime.Now
});
context.SaveChanges();
}
Notifications.Send("New user: " + username);
}
}
Normally I’d be coupled to DataContext, DateTime.Now and my static Notifications.Send method, making unit testing this method particularly difficult. But since C# 6 supports monkey patching, this thing is now perfectly testable and without the otherwise unnecessary interfaces and complexity.
We can patch DataContext (stubbing it, in test parlance) and make it do nothing. We can patch DateTime.Now to give us a more predictable value. And we can certainly patch Notifications.Send so that it doesn’t send anything and just allows us to inspect the message.
Here’s the test:
[Test]
public void Register_WithValidUsername_RegisterUserAndNotifies()
{
User user;
string notification;
// Patch
DateTime.Now = () => new DateTime(1, 1, 1);
DataContext.SaveChanges = (context) =>
{
user = context.Users.FirstOrDefault();
};
Notifications.Send = (msg) =>
{
notification = msg;
};
// Act
new UserService.Register("bob");
// Asset
Assert.That(user.Username, Is.EqualTo("bob"));
Assert.That(user.Created.Year, Is.EqualTo(1));
Assert.That(user.Created.Month, Is.EqualTo(1));
Assert.That(user.Created.Day, Is.EqualTo(1));
Assert.That(notification, Is.EqualTo("New user: bob"));
}
Not Limited To Testing
Monkey patching (also know as duck punching, if you prefer) is not only useful for testing. This new ability to patch stuff means we can replace behaviour in classes that we don’t necessarily own.
Some HTTP library you’re using have a broken URL encoding method? Just patch it. Want to redirect a method to somewhere else without introducing a subclass? Just patch it.
What Does This Mean?
Today was a big day for C# – it just became easier to fall into the pit of success:
-
Testing code is now much easier out of the box since all we have to do is stub it via a good old duck punch to the gut.
-
We don’t have to introduce 5 interfaces purely for the sake of testability when the design doesn’t require such decoupling.
-
All that legacy (otherwise untestable) code is now testable – just patch it.
-
Bugs in code we don’t own just became fixable.
But most importantly, C# gave us back some control and let us decide what’s dangerous and what’s not. C# just became more flexible and gave us a chance to be more awesome with it. C# just trusted us.


Only concern with this is that it could be seen as a shortcut to fix problems with a potential shortish view.
I think anything like this has to be used with care & skill.
Although it does look pretty god damn awesome…
Something like this would have to be used with skill and care, I agree. And this can be said for most other language features. In saying that, people do use (and swear by (see linked video)) such features with skill and care every day in other languages.
So, I guess the question is: would we be better with it? Would not having to introduce interfaces in our code purely for testability make us more productive? Would being able to patch/fix code we don’t own be beneficial in the long run?
Ultimately, I think your language should work for you – you shouldn’t work for your language. Every time I am forced to subclass or extract interface for no other purpose than testability, I’m working for the language.
How does it distinguish between static and instance methods, you monkey patch an instance method on DataContext the exact same way you did static on DateTime
That’s a good question, but really my goal was just to postulate it happening as apposed to suggest how it might work technically.
Perhaps it’s not technically possible to introduce such a thing at this stage, and even more likely is that it’s too costly. But nevertheless, I thought it was an interesting mental experiment to consider what C# would feel like if it did, somehow, happen :)
So, how does Windows 8 look? And is VS2012 any good? Oh, and has Node.JS stormed to supremacy or did it all just fade away? ;)
Seriously though, nice article, and for one I think monkey patching would be an interesting proposition in c#
VS2012 and Windows 8 are both HTML5 and run on Node.JS now.
And thanks Matt. So, wanna help me hack the CLR to implement it? What do you mean you have to wash your hair? :)
Hmm…till then, make it yourself:
http://www.heartysoft.com/composition-when-overriding
Then a newbie should learn C# instead of Java?