nullybool == true

It’s always been a pet peeve of mine to see conditions where a boolean variable is compared to a boolean value.

if (someBoolean == true) // ew!
{
    ...
}
if (someBoolean) // omg, better!
{
    ...
}

It bothers me because it’s redundant. You already have a true or false, do you really need to compare it to true or false to know if it’s true or false?

I picked up this little bugbear back in the VB6 world. As I moved into the .Net realm, I was introduced to a new spin on booleans: Nullable<bool>. At it’s core, it’s still a boolean though, right? So my peeve lived on.

if (nullybool.HasValue && nullybool.Value == true) // blech!
{
    ...
}
if (nullybool.HasValue && nullybool.Value) // omg, yes!
{
    ...
}
if (nullybool.GetValueOrDefault()) // OMG, EVEN BETTER!
{
    ...
}

But alas, I have just learned that comparing nullable booleans to boolean values is actually quite nice. It saves you a lot of .HasValue-ing. I am officially ending my lifelong campaign against removing “== true” and “== false” from any and all code I come across; I’m making exceptions for nully-bools.

if (nullybool.GetValueOrDefault()) // gettin' paid per keystroke?
{
    ...
}
if (nullybool == true) // noice!
{
    ...
}

Now, all that said, there is still a place for HasValue. Sometimes you need to know if the value has actually been set, but I won’t want to see any more nullybool.HasValue && nullybool.Value-business. I’m done with that! (And a new peeve is born…!)

Async/Await Crash Course

I’ve known about Microsoft’s asynchronous programming since hearing the announcement at PDC 2010. I’ve been aware of it, and I’ve dabbled here and there, but I haven’t really gotten into using it as part of my standard toolkit for a variety of reasons. First, it was that the product I was focused on could only use .Net Framework 3.5. Then I was on another product that used .Net 4.0, but we didn’t have much need for performance tuning.

But now I’m in a world where I have access to it AND a need for it–hooray! And so, with that, I present to you my crash course on asynchronous programming in c# using the async and await keywords.

Let me set up a scenario for my examples. Imagine a function that matches records between two systems. Data must be retrieved from each of the two systems before the matching can be performed.

Here’s what a fully-synchronous version of the problem might look like. Note that data is being loaded one-type and one-source at a time, followed by matching for that type.

public void DoMatching()
{
    var fooFromA = GetFooFromA();
    var fooFromB = GetFooFromB();
    Match(fooFromA, fooFromB);
    Console.WriteLine("{0} foo matched!", fooFromB.Count(x => x.IsMatch));
    
    var barFromA = GetBarFromA();
    var barFromB = GetBarFromB();
    Match(barFromA, barFromB);
    Console.WriteLine("{0} bar matched!", barFromB.Count(x => x.IsMatch));
}

public IEnumerable<Foo> GetFooFromA()
{
    var data = new Foo[] { new Foo(1), new Foo(2), new Foo(3) };
    return data;
}

public IEnumerable<Foo> GetFooFromB()
{
    var data = new Foo[] { new Foo(2), new Foo(3), new Foo(4) };
    return data;
}

public IEnumerable<Bar> GetBarFromA()
{
    var data = new Bar[] { new Bar("one"), new Bar("two"), new Bar("three") };
    return data;
}

public IEnumerable<Bar> GetBarFromB()
{
    var data = new Bar[] { new Bar("two"), new Bar("three"), new Bar("four") };
    return data;
}

public void Match(IEnumerable<Foo> fooFromA, IEnumerable<Foo> fooFromB)
{
    foreach (var foo in fooFromB)
    {
        if (fooFromA.Any(x => x.Id == foo.Id))
        {
            foo.IsMatch = true;
        }
    }
}

public void Match(IEnumerable<Bar> barFromA, IEnumerable<Bar> barFromB)
{
    foreach (var bar in barFromB)
    {
        if (barFromA.Any(x => x.Id == bar.Id))
        {
            bar.IsMatch = true;
        }
    }
}

public class Foo
{
    public int Id { get; set; }
    public bool IsMatch { get; set; }
    
    public Foo(int id)
    {
        Id = id;
    }
}

public class Bar
{
    public string Id { get; set; }
    public bool IsMatch { get; set; }
    
    public Bar(string id)
    {
        Id = id;
    }
}

The first thing we can do to optimize this code with async/await is to make the data retrieval methods asynchronous. This is done in just three steps:

  1. Change the return type to Task<T>
  2. Add async to the function declaration
  3. Use await to return the value

If the logic in your function blocks the CPU, like mine which just has a hard-coded result, you can make it async-friendly by executing it via Task.Run.

Here’s what the new, async version of my data-getters.

public async Task<IEnumerable<Foo>> GetFooFromA()
{
    return await Task.Run(() => new Foo[] { new Foo(1), new Foo(2), new Foo(3) });
}

public async Task<IEnumerable<Foo>> GetFooFromB()
{
    return await Task.Run(() => new Foo[] { new Foo(2), new Foo(3), new Foo(4) });
}

public async Task<IEnumerable<Bar>> GetBarFromA()
{
    return await Task.Run(() => new Bar[] { new Bar("one"), new Bar("two"), new Bar("three") });
}

public async Task<IEnumerable<Bar>> GetBarFromB()
{
    return await Task.Run(() => new Bar[] { new Bar("two"), new Bar("three"), new Bar("four") });
}

Okay, so that takes care of half the problem, but now we need to make sure the match functions are executed once the data they need is available. One way to do this would be to use the await keyword, like this:

var fooFromA = GetFooFromA();
var fooFromB = GetFooFromB();
Match(await fooFromA, await fooFromB);

But wait! We don’t want to do that because we’ll be preventing the data retrieval and matching of our Bar records while we process our Foo records. Instead, we can use Task.WhenAll to tell our match function to process once the data it needs becomes available.

var fooFromA = GetFooFromA();
var fooFromB = GetFooFromB();
Task.WhenAll(fooFromA, fooFromB).ContinueWith(t => 
{
    Match(fooFromA.Result, fooFromB.Result);
    Console.WriteLine("{0} foo matched!", fooFromB.Result.Count(x => x.IsMatch));
});

Note that in my ContinueWith block, I’m using the Result property of the asynchronous tasks. It’s safe to use the property since WhenAll makes sure they’re finished before getting there. If we wanted to be extra safe, we could check the status of the Task (t) that’s passed into our anonymous function–probably a good idea to verify that nothing went wrong while retrieving the data.

You’ll also notice that I moved the Console.WriteLine into the ContinueWith block. This needs to happen for two reasons. First, the code’s running asynchronously so the matching wouldn’t have occurred by the time the statement was run. Second, the collection might not be accessible if the task hadn’t completed; you could use the await keyword, but even then you could not guarantee that matching had finished.

So now we’re in business. The data retrievals all occur asynchronously, and matching begins as soon as the requisite data is received for each of our respective data types. We haven’t done anything with our DoMatching function, though. If we want to make it awaitable, we just need to keep track of our work tasks and make use of WhenAll again. Notice that we’ve added the async keyword to our method signature and that void has become Task.

public async Task DoMatching()
{
    var fooFromA = GetFooFromA();
    var fooFromB = GetFooFromB();
    var matchFoos = Task.WhenAll(fooFromA, fooFromB).ContinueWith(t => 
    {
        Match(fooFromA.Result, fooFromB.Result);
        Console.WriteLine("{0} foo matched!", fooFromB.Result.Count(x => x.IsMatch));
    });
    
    var barFromA = GetBarFromA();
    var barFromB = GetBarFromB();
    var matchBars = Task.WhenAll(barFromA, barFromB).ContinueWith(t => 
    {
        Match(barFromA.Result, barFromB.Result);
        Console.WriteLine("{0} bar matched!", barFromB.Result.Count(x => x.IsMatch));
    });
    
    await Task.WhenAll(matchFoos, matchBars);
}

Complete example:

void Main()
{
    DoMatching().Wait();
}

public async Task DoMatching()
{
    var fooFromA = GetFooFromA();
    var fooFromB = GetFooFromB();
    var matchFoos = Task.WhenAll(fooFromA, fooFromB).ContinueWith(t => 
    {
        Match(fooFromA.Result, fooFromB.Result);
        Console.WriteLine("{0} foo matched!", fooFromB.Result.Count(x => x.IsMatch));
    });
    
    var barFromA = GetBarFromA();
    var barFromB = GetBarFromB();
    var matchBars = Task.WhenAll(barFromA, barFromB).ContinueWith(t => 
    {
        Match(barFromA.Result, barFromB.Result);
        Console.WriteLine("{0} bar matched!", barFromB.Result.Count(x => x.IsMatch));
    });
    
    await Task.WhenAll(matchFoos, matchBars);
}

public async Task<IEnumerable<Foo>> GetFooFromA()
{
    return await Task.Run(() => new Foo[] { new Foo(1), new Foo(2), new Foo(3) });
}

public async Task<IEnumerable<Foo>> GetFooFromB()
{
    return await Task.Run(() => new Foo[] { new Foo(2), new Foo(3), new Foo(4) });
}

public async Task<IEnumerable<Bar>> GetBarFromA()
{
    return await Task.Run(() => new Bar[] { new Bar("one"), new Bar("two"), new Bar("three") });
}

public async Task<IEnumerable<Bar>> GetBarFromB()
{
    return await Task.Run(() => new Bar[] { new Bar("two"), new Bar("three"), new Bar("four") });
}

public void Match(IEnumerable<Foo> fooFromA, IEnumerable<Foo> fooFromB)
{
    foreach (var foo in fooFromB)
    {
        if (fooFromA.Any(x => x.Id == foo.Id))
        {
            foo.IsMatch = true;
        }
    }
}

public void Match(IEnumerable<Bar> barFromA, IEnumerable<Bar> barFromB)
{
    foreach (var bar in barFromB)
    {
        if (barFromA.Any(x => x.Id == bar.Id))
        {
            bar.IsMatch = true;
        }
    }
}

public class Foo
{
    public int Id { get; set; }
    public bool IsMatch { get; set; }
    
    public Foo(int id)
    {
        Id = id;
    }
}

public class Bar
{
    public string Id { get; set; }
    public bool IsMatch { get; set; }
    
    public Bar(string id)
    {
        Id = id;
    }
}

Several Patterns for Refactoring Static Classes for Testability

Static classes and methods can be tricky business for unit tests, and I’ve had to do a lot of refactoring them lately to get some tests going. Here are a few different ways to make your static classes test-friendly.

For the examples below, assume we need to refactor the following class to make it more testable:

public static class Foo
{
    public static void Bar()
    {
        // do something
    }
}

Convert to Instance Class

A simple and straightforward solution is to convert your static class to an instance class. If you need to prevent multiple instances from existing, you can implement the singleton pattern in your class. It’s easy to do this, but it can be risky or tedious to implement across a solution depending on how much your static class is being used. For example, if your class is being accessed hundreds or thousands of times across many different projects, you may not want to do this because you’ll have to update each and every caller.

public class Foo : IFoo
{
    private static IFoo Instance { get; set; }
    
    static Foo()
    {
        Instance = new Foo();
    }
    
    private Foo()
    {
    }
    
    public void Bar()
    {
        // do something
    }
}

Keep Static Class, Extract Implementation #1

If you want or need to keep your static classes/methods as static without having to change every caller, you can extract the implementation of your static class to a new instance class and adjust the static class to use that. The implementation class uses the singleton pattern to expose a single static instance that will be used by the static class.

public static class Foo
{
    public static void Bar()
    {
        FooImplementation.Instance.Bar();
    }
}

internal class FooImplementation : IFoo
{
    public static IFoo Instance { get; private set; }
    
    static FooImplementation()
    {
        Instance = new FooImplementation();
    }
    
    private FooImplementation()
    {
    }
    
    public void Bar()
    {
        // do something
    }
}

public interface IFoo
{
    void Bar();
}

This works great, but it does require unit test authors to have knowledge of the new implementation class. This strikes me as slightly non-intuitive for developers since you go to class B to mock the behavior of class A. And that brings us to our next option…

Keep Static Class, Extract Implementation #2

Another option is to tweak the above strategy slightly so that the static property is added to the static class instead of on the implementation instance class. The nice thing about this approach is that you don’t need to have any awareness of the default implementation when providing the static class with an alternate implementation.

public static class Foo
{
    private static IFoo Implementation { get; set; }
    
    static Foo()
    {
        Implementation = new FooImplementation();
    }
    
    public static void Bar()
    {
        Implementation.Bar();
    }
}

internal class FooImplementation : IFoo
{
    public void Bar()
    {
        // do something
    }
}

public interface IFoo
{
    void Bar();
}

Create a Wrapper

Another option is to create a wrapper. Much like the first option presented, this approach has the downside of needing to update all callers to use the wrapper. However, if you are unable to modify the contents of your static class, this may be your best bet.

public static class Foo
{
    public staic void Bar()
    {
        // do something
    }
}

public class FooWrapper : IFoo
{
    private static IFoo Instance { get; set; }
    
    static FooWrapper()
    {
        Instance = new FooWrapper();
    }
    
    private FooWrapper()
    {
    }
    
    public void Bar()
    {
        Foo.Bar();
    }
}

interface IFoo
{
    void Bar();
}