Testing Tidbits: Avoid OrDefault extension methods in tests

Be full of certainty when writing tests – it’s important to define the behaviour you expect, and make your intentions clear for your colleagues and your future self. In following these guidelines, it’s good practice to avoid using SingleOrDefault or FirstOrDefault in your tests, especially in unit tests. Using FirstOrDefault in the following code folds uncertainty into some routine assertions:

var firstThing = myTestObject.Things.FirstOrDefault();

The Things collection should never be empty, but the test checks for a null return value. We could simplify it, removing the assignment and the null check, but the uncertainty remains:


You’ve almost certainly spotted (and if you’re using ReSharper, it will too) that this code has the potential to throw a null reference exception if the code changes and the Things collection contains nothing. That null reference exception is unhelpful in tracking down its cause. Replacing FirstOrDefault with First will indicate the actual problem more clearly with an exception stating that "The source sequence is empty". It’s also a signal to others that you always expect Things to contain one or more items:


Be confident in your assertions, eliminate uncertainty!

Posted in C#, Testing | Tagged , , | Leave a comment

Reblog: How To Spot The Legacy Code Writer In Your Company (Hint: It’s You)

An article I read recently with a really interesting perspective on legacy code, and how pushing back against the build-up of legacy code with refactoring is absolutely vital to a project’s long-term health.

Arialdo Martini

Also available in Czech, kindly translated by Aleš Roubíček


Writing Legacy Code* is a distributed activity.

*In Working Effectively with Legacy Code Michael Feathers defines Legacy Code as “Code with no tests“, which reflects the perspective of legacy code being difficult to work with. I’ll stick to this definition.

Long version

Oh, no! Bad code again

You have been assigned a new task.

Your mission: to add a simple feature to a Corporate project. You know almost nothing about it, but the feature request sounds feasible. You can easily accomplish the task.


This is what you think. Until you open the code base.

View original post 1,647 more words

Posted in Clean Code | Tagged , | Leave a comment

Using underscore to denote unused parameters in C# lambdas

In this recent answer on StackOverflow, it seems I used a somewhat unorthodox way of declaring an empty lambda, and thought a brief explanation would make a good blog post.

Usually, a lambda method is declared with just its parameter names – the types are inferred. In the case of an Action for a traditional EventHandler event, for example, we have the sender as an object, and some event arguments that are, or are derived from, EventArgs:

public event EventHandler Updated;


this.Updated += (sender, args) =>
    // Take some action when invoked

If we never use an argument that’s passed, we can adopt a convention of replacing its parameter name with one or more underscores:

this.Updated += (_, args) =>
    // Some action that just makes use of args

this.Updated += (_, __) =>
    // Some action that doesn't use either parameter

It’s also useful for declaring empty lambdas, which was in the answer above:

DoExport((_, __) => { });

I think that this convention helps with readability and code comprehension – it’s immediately obvious that a parameter isn’t used in a lambda method, and it shortens the definition. If the parameter becomes used, it can simply be given its name back. One of the comments on the answer above called this “Very Scala-esque!” – and in fact, it is one of the (many) uses of underscore in Scala.

Posted in C# | Tagged , , , | Leave a comment

Avoid using new to create Tuples

Ever come across code like this being used to create a Tuple?

var someTuple = new Tuple<ILongInterfaceName, ILongerInterfaceName, IReallyLongInterfaceName>(firstItem, secondItem, thirdItem);

Ick. The generic type arguments obscure the constructor, and the whole thing is entirely too long to sit on a single line for my liking – even with only three types, it’s considerably longer than 100 characters. Sure, we could drop the generic type parameters on to separate lines, maybe do the same with the constructor arguments, but it’s still going to be a mess.

So, what to do? Well, there’s a much better, if seemingly less well-known, way of constructing a Tuple – the Create method:

var someTuple = Tuple.Create(firstItem, secondItem, thirdItem);

Use the Create method and its overloads to infer the types – you’ll save yourself the trouble of typing them out, and produce much more readable code in the process.

Posted in C# | Tagged | Leave a comment

Testing Tidbits: Checking Static Methods Throw Correctly with FluentAssertions

The usual way of testing that a method throws an expected exception with FluentAssertions involves using the Invoking and ShouldThrow extension methods:

    .Invoking(x => x.SomeMethod(-15))
        "Negative values not supported!");

Being an extension method, Invoking requires an object to operate on, so if we’re attempting to test a static method, this isn’t going to work:

    .Invoking(x => x.SomeMethod(-15))
        "Negative values not supported!");

Conveniently though, ShouldThrow takes Action as its first parameter, so we can do away with Invoking altogether by putting the call to test in an Action and calling ShouldThrow on it:

Action callingWithANegativeValue =
    () => StaticTestClass.SomeMethod(-15);

    "Negative values not supported!");

A little bit more verbose, but equally effective.

Posted in C# | Tagged , , , | Leave a comment

Downloading part of a website to read offline

I wanted to download a portion of a website to read offline – the index, and the pages it linked to. I couldn’t seem to find a web scraper for Windows that could do what I needed though, so I followed this guide to install wget in Git Bash, and used that instead:

wget -r --level=1 -k -p http://fgiesen.wordpress.com/2011/07/09/a-trip-through-the-graphics-pipeline-2011-index/

-r is recursive
--level=1 is the depth of recursion from the index page, the depth of links to follow
-k converts the links in the pages downloaded so that they point to local copies
-p gets everything requires to display each page – images, stylesheets, etc.

wget is hugely configurable for many different scenarios, but for this most basic of uses, the handful of options above did exactly what I needed.

Posted in Internet | Tagged | Leave a comment

Deleting all similarly-named Elasticsearch indexes using a wildcard

At work, our system makes extensive use of Elasticsearch, and we have a lot of integration tests around the code that interacts with it. We create a new in-memory index for each integration test, and delete it after the test has run. Occasionally, these indexes don’t get cleanly removed, leaving a large number of them that need to be manually deleted. This is a time-consuming nuisance. There’s a seemingly-undocumented shortcut in Elasticsearch that can really help in this situation, though – deleting indexes with a wildcard.

Usually, to delete an index, you issue a DELETE call with the full name of the index:

curl -XDELETE localhost:9200/[nameOfIndexToDelete]

To distinguish them from other indexes, all of our test indexes have the same prefix: test-inmemory-. So, to delete every index with a name that beings with this prefix, you can specify the prefix with a wildcard:

curl -XDELETE localhost:9200/test-inmemory-*

This has been a real time-saver.

Posted in Elasticsearch | Tagged , | Leave a comment