January 2013 Blog Posts

Async Lambdas

Today I learned something new and I love that!

I was looking at some code that looked like this:

try
{
    await obj.GetSomeAsync();
    Assert.True(false, "SomeException was not thrown");
}
catch (SomeException)
{
}

That’s odd. We’re using xUnit. Why not use the Assert.Throws method? So I tried with the following naïve code.

Assert.Throws<SomeException>(() => await obj.GetSomeAsync());

Well that didn’t work. I got the following helpful compiler error:

error CS4034: The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

Oh, I never really thought about applying the async keyword to a lambda expression, but it makes total sense. So I tried this:

Assert.Throws<SomeException>(async () => await obj.GetSomeAsync());

Hey, that worked! I rushed off to tell the internets on Twitter.

But I made a big mistake. That only made the compiler happy. It doesn’t actually work. It turns out that Assert.Throws takes in an Action and thus that expression doesn’t return a Task to be awaited upon. Stephen Toub explains the issue in this helpful blog post, Potential pitfalls to avoid when passing around async lambdas.

Ah, I’m gonna need to write my own method that takes in a Func<Task>. Let’s do this!

I wrote the following:

public async static Task<T> ThrowsAsync<T>(Func<Task> testCode)
      where T : Exception
{
  try
  {
    await testCode();
    Assert.Throws<T>(() => { }); // Use xUnit's default behavior.
  }
  catch (T exception)
  {
    return exception;
  }
  // Never reached. Compiler doesn't know Assert.Throws above always throws.
  return null;
}

Here’s an example of a unit test (using xUnit) that makes use of this method.

[Fact]
public async Task RequiresBasicAuthentication()
{
  await ThrowsAsync<SomeException>(async () => await obj.GetSomeAsync());
}

And that works. I mean it actually works. Let me know if you see any bugs with it.

Note that you have to change the return type of the test method (fact) from void to return Task and mark it with the async keyword as well.

So as I was posting all this to Twitter, I learned that Brendan Forster (aka @ShiftKey) already built a library that has this type of assertion. But it wasn’t on NuGet so he’s dead to me.

But he remedied that five minutes later.

Install-Package AssertEx.

So we’re all good again.

If I were you, I’d probably just go use that. I just thought this was an enlightening look at how await works with lambdas.

Fitbit Me

Back in March of last year, Stephen Wolfram wrote a blog post, The Personal Analytics of My Life. It’s a fascinating look at the data he’s accumulated over years about his own personal activities and habits such as daily incoming and outgoing email.

Since I read that, I’ve been fascinated about the idea of how personal data analytics might prove useful to me. It turns out I found an application to my health.

In my series on The Real Pain of Software Development (part1 and part2), I talked about my history with pain related to work and the various measures I took to remedy that pain including intense physical and occupational therapy.

I neglected to mention was how much difference a bit of weight loss makes. A single pound reduces the force on your joints, back, and other muscles an immense amount over the course of a day, week, or years. I am now more aware of how much pain I feel ebbs and flows as my weight does.

Sometime last year, GitHub gave all of us a Fitbit. It’s a little device that tracks the number of steps you take during the day. It can also track vertical distance changes and if you’re diligent, how much sleep you get. It posts all the data online so you can take a look at your numbers and compare to friends.

It wasn’t long before my co-workers hooked it up to Hubot (just another example of how chat is important to us and is at the center of how we work). Here’s a screenshot of the /fitbit me command which shows the leaderboards for step counts in the past 7 days. I blocked out names for privacy reasons, though I bet the top four would love to be unredacted.

fitbit-me

What I love about this is it adds an element of friendly competition to the mix. There’s absolutely NOTHING riding on this other than pride. Yet, it’s amazing how motivating this is. I now take a long walk to get coffee every day because I want to be up there near the top. And there’s no downsides to that. Maybe it’s the wrong motivation, but it’s definitely the right result. The evidence for this result is in the following.

I also happened to purchase the FitBit Aria Wi-Fi scale because I love me them stats. As you can see from the graph, the /fitbit me motivation is effective.

2012-now-weight

Unfortunately, I injured my knee snowboarding a couple weeks ago and have been sick the past few days so it’s starting to trend slightly up. But since I’ve had the scale, I’ve lost 6.3 lbs overall. This isn’t only due to the FitBit. We recently started a single subscription to BistroMD to supplement our cooking efforts since we both work and I work from home. I’ve found portion control a lot easier when it’s controlled for you.

FitBit can also track sleep, but this is not as automatic as step counting. You have to remember to wear it at night and put it in sleep mode. It’s a bit high maintenance.

2012-sleep-over-time

Also, it seems to count nights that you forget to set it as a day with 0 hours of sleep, which is not really what I want. Based on this graph you might incorrectly assume I averaged from 3 to 6 hours of sleep a night over the past year. Clearly that’s not correct or I’d be a raging hallucinatory lunatic by now. I know, some of you think I am such a beast, but if so it’s for other reasons, not due to lack of sleep.

I hope to be more diligently track my sleep patterns this year to see if there are any interesting correlations between the amount of sleep I get, my fitness level, my mood, and my GitHub contributions graph. Heh.

One thing I wish FitBit did better is provide better graphs for seeing my step counts over time. For example, here’s what I could find to see my step counts over the past 30 days.

steps-over-last-30-days

I’d love to see a graph of my steps over the year in fine detail.

Speaking of step counts, see that big spike in January, that’s the GitHub Winter Summit, our all company meeting in San Francisco. The way that spikes might give you the impression that we’re all health freaks and the summit is a very physical endeavor. Well, maybe.

The following is a breakdown of one of a couple of those days.

2013-01-17-stepsJanuary 17, 2013: 23,285 (approx 10.69 miles)

2013-01-18-stepsJanuary 18, 2013: 24,512 steps (approx: 11.35 miles)

Notice the hours of the big spikes. Yeah, we like to dance late at night.

Notice the big midday bump on the second day? That was a scavenger hunt that took us all around the great city of San Francisco.

All in all, I’m pretty happy with the FitBit and like how the data driven lifestyle it encourages has been a net positive for me. Your mileage may vary of course.

Some downsides to the FitBit is that it’s easy to lose. It’s easy to forget about it and launder it. It’s somewhat easy to break. Mine’s survived so far, but not without a chip or two. Also, it requires charging almost every day or at least every other day. Also, I’m not aware of a way to get the absolute raw data even with the premium account.

I’d be willing to pay money to get the raw data and create my own graphs. FitBit isn’t the only personal fitness tracker out there, but it’s the only one I’ve tried and I’m a big fan. I wouldn’t mind trying others, but much like the network effects of other social networks, the fact that many of my friends and co-workers are all on FitBit will keep me tied to it for now.

UPDATE: Looks like there is a FitBit API. I’ll have to play around with it. Thanks to @geeksmeetgirl for pointing it out to me.

Hidden Pitfalls With Object Initializers

I love automation. I’m pretty lazy by nature and the more I can offload to my little programmatic or robotic helpers the better. I’ll be sad the day they become self-aware and decide that it’s payback time and enslave us all.

But until that day, I’ll take advantage of every bit of automation that I can.

the-matrix-humans

For example, I’m a big fan of the Code Analysis tool built into Visual Studio. It’s more more commonly known as FxCop, though judging by the language I hear from its users I’d guess it’s street name is “YOU BIG PILE OF NAGGING SHIT STOP WASTING MY TIME AND REPORTING THAT VIOLATION!”

Sure, it has its peccadilloes, but with the right set of rules, it’s possible to strike a balance between a total nag and a helpful assistant.

As a developer, it’s important for us to think hard about our code and take care in its crafting. But we’re all fallible. In the end, I’m just not smart enough to remember ALL the possible pitfalls of coding ALL OF THE TIME such as avoiding the Turkish I problem when comparing strings. If you are, more power to you!

I try to keep the number of rules I exclude to a minimum. It’s saved my ass many times, but it’s also strung me out in a harried attempt to make it happy. Nothing pleases it. Sure, when it gets ornery, it’s easy to suppress a rule. I try hard to avoid that because suppressing one violation sometimes hides another.

Here’s an example of a case that confounded me today. The following very straightforward looking code ran afoul of a code analysis rule.

public sealed class Owner : IDisposable
{
    Dependency dependency;

    public Owner()
    {
        // This is going to cause some issues.
        this.dependency = new Dependency { SomeProperty = "Blah" };
    }

    public void Dispose()
    {
        this.dependency.Dispose();
    }
}

public sealed class Dependency : IDisposable
{
    public string SomeProperty { get; set; }
        
    public void Dispose()
    {
    }
}

Code Analysis reported the following violation:

CA2000 Dispose objects before losing scope
In method 'Owner.Owner()', object '<>g__initLocal0' is not disposed along all exception paths. Call System.IDisposable.Dispose on object '<>g__initLocal0' before all references to it are out of scope.

That’s really odd. As you can see, dependency is disposed when its owner is disposed. So what’s the deal?

Can you see the problem?

A Funny Thing about Object Initializers

A2600_PitfallThe big clue here is the name of the variable that’s not disposed, <>g__initLocal0. As Phil Karlton once said, emphasis mine,

There are only two hard things in Computer Science: cache invalidation and naming things.

Naming may be hard, but I can do better than that. Clearly the compiler came up with that name, not me. I fired up Reflector to see the generated code. The following is the constructor for Owner.

public Owner()
{
    Dependency <>g__initLocal0 = new Dependency {
        SomeProperty = "Blah"
    };
    this.dependency = <>g__initLocal0;
}

Aha! So we can see that the compiler generated a temporary local variable to hold the initialized object while its properties are set, before assigning it to the member field.

So what’s the problem? Well if for some reason setting SomeProperty throws an exception, <>g__initiLocal0 will never be disposed. That’s what the Code Analysis is complaining about. Note that if an exception is thrown while setting that property, my member field is also never set to the instance. So it’s a dangling undisposed instance.

So what’s the Plan Stan?

Well the fix to keep code analysis happy is simple in this case.

public Owner()
{
    this.dependency = new Dependency();
    this.dependency.SomeProperty = "Blah";
}

Don’t use the initializer and set the property the old fashioned way.

This shuts up CodeAnalysis, but did it really solve the problem? Not in this specific case because we happen to be inside a constructor. If the Owner constructor throws, nobody is going to dispose of the dependency.

As Greg Beech wrote so long ago,

From this we can ascertain that if the object is not constructed correctly then the reference to the object will not be assigned, which means that no methods can be called on it, so the Dispose method cannot be used to deterministically clean up managed resources. The implication here is that if the constructor creates expensive managed resources which need to be cleaned up at the earliest opportunity then it should do so in an exception handler within the constructor as it will not get another chance.

So a more robust approach would be the following.

public Owner()
{
    this.dependency = new Dependency();
    try
    {
        this.dependency.SomeProperty = "Blah";
    }
    catch (Exception)
    {
        dependency.Dispose();
        throw;
    }       
}

This way, if setting the properties of Dependency throws an exception, we can dispose of it properly.

Why isn’t the compiler smarter?

I’m not the first to run into this pitfall with object initializers and disposable instances. Ayende wrote about a related issue with using blocks and object initializers back in 2009. In that post, he suggests the compiler should generate safe code for this scenario.

It’s an interesting question. Whenever I think of such questions, I put on my Eric Lippert hat and hear his proverbial voice (I’ve never heard his actual voice but I imagine it to be sonorous and profound) in my head saying:

I'm often asked why the compiler does not implement this feature or that feature, and of course the answer is always the same: because no one implemented it. Features start off as unimplemented and only become implemented when people spend effort implementing them: no effort, no feature. This is an unsatisfying answer of course, because usually the person asking the question has made the assumption that the feature is so obviously good that we need to have had a reason tonot implement it. I assure you that no, we actually don't need a reason to not implement any feature no matter how obviously good. But that said, it might be interesting to consider what sort of pros and cons we'd consider if asked to implement the "silently put inferred constraints on class type parameters" feature.

The current implementation of object initializers seems correct for most cases. The only time it breaks down is in the case of disposable types. So let’s think about some possible solutions.

Why the intermediate variable?

First, let’s look at why the intermediate local variable. My initial knee-jerk reaction (ever notice how often your knee-jerk reaction makes you sound like jerk?) was that the intermediate variable is unecessary. But I thought about it some more and came up with the scenario. Suppose we’re setting a property to the value of an object created via an initializer.

this.SomePropertyWithSideEffects = new Dependency { Prop = 42 };

The way to do this without an intermediate local variable is the following.

this.SomePropertyWithSideEffects = new Dependency();
this.SomePropertyWithSideEffects.Prop = 42;

The first code block only calls the setter of SomePropertyWithSideEffects. But the second code block calls both the getter and setter. That’s pretty different behavior.

Now imagine we’re setting multiple properties or using a collection initializer with multiple items instead. We’d be calling that property getter multiple times. Who knows what awful side-effects that might produce. Sure, side effects in property getters are bad, but as I’ll point out later, there’s another reason this approach is fraught with error.

The intermediate local variable is necessary to ensure the object is only assigned after it’s fully constructed.

Dispose it for me?

So given that, let’s try implementing the the Owner constructor of my previous example the way a compiler might do it.

public Owner()
{
    var <>g__initLocal0 = new Dependency();
    try
    {
        <>g__initLocal0.SomeProperty = "Blah";
    }
    catch (Exception)
    {
        <>g__initLocal0.Dispose();
        throw;
    }
    this.dependency = <>g__initLocal0;
}

That’s certainly seems much safer, but there’s still a potential flaw. It’s optimistically calling dispose on the object when the exception is thrown. What if I didn’t want to call dispose on it even though it’s disposable? Maybe the Dispose method of this specific object deletes your hard-drive and plays Justin Bieber music when invoked. In 99.9 times out of 100, you would want Dispose called in this case. But this is still a change in behavior and I can understand why the compiler might not risk it.

Perhaps the compiler could attempt to figure out if that instance eventually gets disposed and do the right thing. All you have to do find a flaw in Turing’s proof of the Halting Problem. No problem, right?

Perhaps we could be satisfied with good enough. Dispose it always and just say that’s the behavior of object initializers. It’s probably too late for that change as that’d be a breaking change. It’d be one I could live with honestly.

Let me dispose it

Perhaps the problem isn’t that we want the compiler to automatically dispose of the intermediate object in the case of an exception. What we really want is the assignment to  happen no matter what so we can dispose of it in our code if an exception is thrown. Perhaps the compiler can generate code that would allow us to do this in our code.

public Owner()
{
    try
    {
        this.dependency = new Dependency { SomeProperty = "blah" };
    }
    catch (Exception)
    {
        if (this.dependency != null)
            this.dependency.Dispose();
    }
}

What might the generated code look like in this case?

public Owner()
{
    var <>g__initLocal0 = new Dependency();
    this.dependency = <>g__initLocal0;
    <>g__initLocal0.SomeProperty = "Blah";
}

That’s not too shabby. We got rid of the try/catch block that we had to introduce previously, and if an exception is thrown in the property setter, we can clean up after it. I’m a genius!

Not so fast Synkowski. There’s a potential problem here. Suppose we’re not inside a constructor, but rather are in a method that’s setting a shared member.

public void DoStuff()
{
    var <>g__initLocal0 = new Dependency();
    this.dependency = <>g__initLocal0;
    <>g__initLocal0.SomeProperty = "Blah";
}

We’ve now introduced a possible race condition if this method is used in an async or multithreaded environment.

Notice that after this.dependency is set to the local incomplete instance, but before the local property is set, there’s room for another thread to modify this.dependency in some way right in that gap leading to indeterminate results. That’s definitely a change you wouldn’t want the compiler doing.

In fact, this same issue affects my earlier proposal of not using an intermediate variable.

So about that Code Analysis

Note that I didn’t specifically address Ayende’s case. In his case, the initializer is in a using block. That seems like a more tractable problem for the compiler to solve, but this post is getting long as it is and it’s time to wrap up. Maybe someone else can analyze that case for shits and giggles.

In my case, we’re setting a member that we plan to dispose later. That’s a much harder (if not impossible) nut to crack.

And here we get to the moral of the story. I get a lot more work done when I don’t stop every hour to write a blog post about some interesting bug I found in my code.

No wait, that’s not it.

The point here is that code analysis is a very helpful tool for writing more robust and correct code. But it’s just an assistant. It’s not a safety net. It’s more like an air bag. It’ll keep you from splattering your brains on the dashboard, but you can still totally wreck your car and break that nose if you’re not careful at the wheel.

Here’s an example where automated tools can both lead you into an accident, but save your butt at the last second.

If you use Resharper (another tool with its own automated analysis) like I do and you write some code in a constructor that doesn’t use an object initializer, you’re very likely to see this (with the default settings).

resharper-nag

See that green squiggly under the new keyword just inviting, no begging, you to hit ALT+ENTER and convert that bad boy into an object initializer? Go ahead, it seems to suggest. What could go wrong? Oh it could cause you to now leak a resource as pointed out earlier.

I often like to hit CTRL E + CTRL C in Resharper to reformat my entire source file to be consistent with my coding standards. Depending on how you set up the reformatting, such an automatic action could easily change this code from working code to subtly broken code.

I still have to pay careful attention to what it’s doing. It’s easy to get lulled into a sense of safety when performing automatic refactorings. But you can’t trust it one hundred percent. You are the one who is responsible, not the tools. You are the one in control.

Fortunately in this case, Code Analysis brought this issue to my attention. And in doing so, pointed out an interesting topic for a blog post. Yay automation!

Mitigate The Billion Dollar Mistake with Aspects

Tony Hoare, the computer scientist who implemented null references in ALGOL calls it his “billion-dollar mistake.”

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

It may well be that a billion is a vast underestimate. But if you’re going to make a mistake, might as well go big. Respect!

To this day, we pay the price with tons of boilerplate code. For example, it’s generally good practice to add guard clauses for each potentially null parameter to a public method.

public void SomeMethod(object x, object y) {
  // Guard clauses
  if (x == null)
    throw new ArgumentNullException("x");
  if (y == null)
    throw new ArgumentNullException("y");

  // Rest of the method...
}

While it may feel like unnecessary ceremony, Jon Skeet gives some good reasons why guard clauses like this are a good idea in this StackOverflow answer:

Yes, there are good reasons:

  • It identifies exactly what is null, which may not be obvious from a NullReferenceException
  • It makes the code fail on invalid input even if some other condition means that the value isn't dereferenced
  • It makes the exception occur before the method could have any other side-effects you might reach before the first dereference
  • It means you can be confident that if you pass the parameter into something else, you're not violating theircontract
  • It documents your method's requirements (using Code Contracts is even better for that of course)

I agree. The guard clauses are needed, but it’s time for some Real Talk™. This is shit work. And I hate shit work.

In this post,

  • I’ll explain the idea of non-nullable parameters and why I didn’t use CodeContracts in the hopes that heads off the first 10 comments asking “why didn’t you use CodeContracts dude?”
  • I’ll cover an approach using PostSharp to automatically validate null arguments.
  • I’ll then explain how I hope to create an even better approach.

Stick with me.

Non Null Parameters

With .NET languages such as C#, there’s no way to prevent a caller of a method from passing in a null value to a reference type argument. Instead, we simply end up having to validate the passed in arguments and ensure they’re not null.

In practice (at least with my code), the number of times I want to allow a null value is far exceeded by the number of times a null value is not valid. What I’d really like to do is invert the model. By default, a parameter cannot be null unless I explicitly say it can. In other words, make allowing null opt-in rather than opt-out as it is today.

I recall that there was some experimentation around this by Microsoft with the Spec# language that introduced a syntax to specify that a value cannot be null. For example…

public void Foo(string! arg);

…defines the argument to the method as a non-nullable string. The idea is this code would not compile if you attempt to pass in a null value for arg. It’s certainly not a trivial change as Craig Gidney writes in this post. He covers many of the challenges in adding a non-nullable syntax and then goes further to provide a proposed solution.

C# doesn’t have such a syntax, but it does have Code Contracts. After reading up on it, I really like the idea, but for me it suffers from one fatal flaw. There’s no way to apply a contract globally and then opt-out of it in specific places. I still have to apply the Contract calls to every potentially null argument of every method. In other words, it doesn’t satisfy my requirement to invert the model and make allowing null opt in rather than opt out. It’s still shit work. It’s also error-prone and I’m too lazy a bastard to get it right in every case.

IL Rewriting to The Rescue

So I figured I’d go off the deep end and experiment with Intermediate Language (IL)weaving with PostSharp to insert guard clauses automatically. Usually, any time I think about rewriting IL, I take a hammer to my head until the idea goes away. A few good whacks is plenty. However in this case, I thought it’d be a fun experiment to try. Not to mention I have a very hard head.

I chose to use PostSharp because it’s easy to get started with and it provides a simple, but powerful, API. It does have a few major downsides for what I want to accomplish that I’ll cover later.

I wrote an aspect, EnsureNonNullAspect, that you apply to a method, a class, or an assembly that injects on null checks for all public arguments and return values in your code. You can then opt out of the null checking using the AllowNullAttribute.

Here’s some examples of usage:

using NullGuard;

[assembly: EnsureNonNullAspect]

public class Sample 
{
    public void SomeMethod(string arg) {
        // throws ArgumentNullException if arg is null.
    }

    public void AnotherMethod([AllowNull]string arg) {
        // arg may be null here
    }

    public string MethodWithReturn() {
        // Throws InvalidOperationException if return value is null.
    }
   
    // Null checking works for automatic properties too.
    public string SomeProperty { get; set; }

    [AllowNull] // can be applied to a whole property
    public string NullProperty { get; set; }

    public string NullProperty { 
        get; 
        [param: AllowNull] // Or just the setter.
        set; 
}

For more examples, check out the automated tests in the NullGuard GitHub repository.

By default, the attribute only works for public properties, methods, and constructors. It also validates return values, out parameters, and incoming arguments.

If you need more fine grained control of what gets validated, the EnsureNonNullAspect accepts a ValidationFlags enum. For example, if you only want to validate arguments and not return values, you can specify: [EnsureNonNullAspect(ValidationFlags.AllPublicArguments)].

Downsides

This approach requires that the NullGuard and PostSharp libraries are redistributed with the application. Also, the generated code is a bit verbose. Here’s an example of the generated code of a previously one line method.

Another downside is that you’ll need to install the PostSharp Visual Studio extension and register for a license before you can fully use my library. The license for the free community edition is free, but it does add a bit of friction just to try this out.

I’d love to see PostSharp add support for generating IL that’s completely free of dependencies on the PostSharp assemblies. Perhaps by injecting just enough types into the rewritten assembly so it’s standalone.

Try it!

To try this out, install the NullGuard.PostSharp package from NuGet.  (It’s a pre-release library so make sure you include preleases when you attempt to install it).

Install-Package NullGuard.PostSharp –IncludePrelease

Make sure you also install the PostSharp Visual Studio extension.

When you install the NuGet package into a project, it should modify that project to use PostSharp. If not, you’ll need to add an MSBuild task to run PostSharp against your project. Just look at Tests.csproj file in the NullGuard repository for an example.

If you just want to see things working, clone the NullGuard repository and run the unit tests.

File an issue if you have ideas on how to improve it or anything that’s wonky.

Alternative Approaches and What’s Next?

NullGuard.PostSharp is really an experiment. It’s my first iteration in solving this problem. I think it’s useful in its current state, but there are much better approaches I want to try.

  • Use Fody to write the guard blocks. Fody is an IL Weaver tool written by Simon Cropp that provides an MSBuild task to rewrite IL. The benefit of this approach is there is no need to redistribute parts of Fody with the application. The downside is Fody is much more daunting to use as compared to PostSharp. It leverages Mono.Cecil and requires a decent understanding of IL. Maybe I can convince Simon to help me out here. In the meanwhile, I better start reading up on IL. I think this will be the next approach I try. UPDATE: Turns out that in response to this blog post, the Fody team wrote NullGuard.Fody that does exactly this!
  • Use T4 to rewrite the source code. Rather than rewrite the IL, another approach would be to rewrite the source code much like T4MVC does with T4 Templates. One benefit of this approach is I could inject code contracts and get all the benefits of having them declared in the source code. The tricky part is doing this in a robust manner that doesn’t mess up the developer’s workflow.
  • Use Roslyn. It seems to me that Roslyn should be great for this. I just need to figure out how exactly I’d incorporate it. Modify source code or update the IL?
  • Beg the Code Contracts team to address this scenario. Like the Temptations, I ain’t too proud to beg.

Yet another alternative is to embrace the shit work, but write an automated test that ensures every argument is properly checked. I started working on a method you could add to any unit test suite that’d verify every method in an assembly, but it’s not done yet. It’s a bit tricky.

If you have a better solution, do let me know. I’d love for this to be handled by the language or Code Contracts, but right now those just don’t cut it yet.

Reflections on 2012

I wasn’t prepared to write an end-of-year blog post given the impending destruction of the world via a Mayan prophesied cataclysmic fury. But since that didn’t pan out I figured I’d better get typing.

reflections

Those of us that are software developers shouldn’t be too surprised that the world didn’t end. After all, how often do projects come in on time within the estimated date amirite?! (high five to all of you).

Highlights of 2012

This year has just been a blast. As my kids turn five and three, my wife and I find them so much more fun to hang out with. Also, this year I reached the one year mark at the best place to work ever. Here’s a breakdown of some of the highlights from the year for me.

  • January Twice a year we have an all-company summit where we get together, give talks, plan, and just have a great time together. This was my first one and I loved every moment of it.
  • February The MVP summit was in town. I wasn’t eligible to be an MVP as a recently departed employee, but I was eligible to host my first GitHub Drinkup for all the MVPs and others in town. We had a big crowd and a great time.
  • March I travelled to the home of the Hobbits, New Zealand to give a keynote at CodeMania.
  • April My family and I visited Richard Campbell and his family in the Vancouver area. I also recorded a Hanselminutes podcast.
  • May We released GitHub for Windows in May. I also visited GitHub HQ this month for a mini-summit with the other native app teams and recorded more podcasts including Herding Code and Deep Fried Bytes.
  • June I spoke at NDC in Oslo Norway. Had a great conference despite the awkward “Azure Girls” incident.
  • July Gave a last minute talk at ASPConf. The software I used to record it crashed and so there’s no recording of this talk sadly.
  • August Back in San Francisco for the GitHub all company summit. I corner Skrillex and force him to take a photo with me.
  • September Family vacation to Oahu Hawaii. I also end up giving a talk to a local user group and hosting a drink up. And my son started Kindergarten.
  • October I spoke at MonkeySpace and got really fired up about the future of Open Source in the .NET world.
  • November At the end of the month I was a guest on the .NET Rocks Roadshow. We had a rollicking good time. I went on a private tour of SpaceX with the fellas. We took the RV to the venue and I got to sample some of the Kentucky Whiskey they collected on their travels before recording a show on Git, GitHub, NuGet, and the non-hierarchical management model we have at GitHub.
  • December This was a quiet month for me. No travels. No talks. Just hacking on code, spending time with the family, and celebrating one year at GitHub. Oh, I also loved watching this Real Life Fruit Ninja to Dubstep video. Perhaps the highlight of 2013.

Top 3 Blog Posts by the numbers

As I did in 2010, I figured I’d post my top three blog posts according to the Ayende Formula.

  • Introducing GitHub for Windows introduces the Git and GitHub client application my team and I worked on this past year (103 comments, 68,672 web views, 25,048 aggregator views).
  • It’s the Little Things About ASP.NET MVC 4 highlights some of the small improvements in ASP.NET MVC 4 that are easy to overlook, but are nice for those that need them (49 comments 56900 web views, 26,044 aggregator views)
  • Structuring Unit Tests covers a nice approach to structuring unit tests for C# developers that I learned from others. This post was written in January which might help explain why it’s in the top three (52 comments, 41,852 web views, 26,073 aggregator views).

My Favorite three posts

These are the three posts that I wrote that were my favorites.

  • You Don’t Need a Thick Skin describes the realization that rather than develop a thick skin, I should focus on developing more empathy for folks that use my software.
  • One year at GitHub is a look back at my year at GitHub and how much I’m enjoying working there.
  • How to Talk to Employees argues that the way to talk to employees is simply the way you’d want to be addressed.

You People

Enough about me, let’s talk about you. As I did in my 2010 post, I thought it’d be fun to post some numbers.

According to Google Analytics:

  • Hello Visitors! 1,880,184 absolute unique visitors (up 6.15% from 2011) made 2,784,021 (down half a %) visits to my blog. came from 223 countries/territories. Most of you came from the United States (875,837) followed by India (267,164) with the United Kingdom (221,727) in third place.
  • Browser of choice: Just two years ago, most of my visitors used Firefox. Now it’s Google Chrome with 45.84%. In second place at 26.37% is Firefox  with IE users at 19.08%. Safari is next at 4% with Opera users still holding on to 2%. I really need to stop making those Opera user jokes. You guys are persistent!
  • Operating System: As I expected, most of you (87.16%) are on Windows, but that number seems to decline every year. 5.71% on a Mac and 2.24% on Linux. The mobile devices are a tiny percentage, but I would imagine that’ll pick up a lot next year.
  • What you read: The blog post most visited in 2012 was written in 2011, C# Razor Syntax Quick Reference with 119,962 page views.
  • How’d you get here: Doesn’t take a genius to guess that most folks come to my blog via Google search results (1,691,540), which probably means most of you aren’t reading this. Winking smile StackOverflow moves to second place (292,670) followed closely by direct visitors (237,862).

My blog is just a single sample, but it’s interesting to me that these numbers seem to reflect trends I’ve seen elsewhere.

Well that’s all I have for 2012. I’m sure there are highlights I forgot to call out that are more memorable or important than the ones I listed. I’m bad at keeping track of things.

One big highlight for me is all the encouraging feedback, interesting comments, insightful thoughts, etc. that I’ve received from many of you in the past year either through comments on my blog or via Twitter. I appreciate it and I hope many of you have found something useful in something I’ve written on my blog or on Twitter. I’ll work hard to provide even more useful writings in the next year.

Happy New Year and I hope that 2013 is even better for you than 2012!