Unit Testing Randomness
The previous posts in this series detailed a number of ways that I had seen System.Random be misused in responses to a coding challenge we ask prospective employees to complete, and described ways to avoid these pitfalls.
The previous posts in this series detailed a number of ways that I had seen System.Random be misused in responses to a coding challenge we ask prospective employees to complete, and described ways to avoid these pitfalls.
The last error I’ve seen in using System.Random is to use a single instance of the class in an application that calls .Next in multiple threads. Twenty-one of the submissions had this problem, and, to be fair, so did I in my original response to our coding test.
My discussion of System.Random pitfalls so far this series, and particularly the post on seeding, has been based on the reference source for .Net Framework.
Another basic error in using System.Random is to use a new instance of the class for each call to .Next.
Another error I saw in our coding test submissions was that of incorrectly seeding the random number generator. Before I show you the coding issues I saw in the test submissions, we need to understand what seeding actually does.
.Next(...)
The most basic error in using System.Random is to get the parameters for the Next method wrong. Part of our coding tests involves generating a random key value from key0 to key9.
We’ve been interviewing for a new position at work recently, and we give all our candidates a coding test to do, usually between the first and second interview. The test involves design around caching of a key/value store in a multi-threaded system. Part of the test requires generating a random set of keys for exercising the cache. I’ve reviewed submissions from candidates so far and, to my surprise, not a single one used System.Random correctly.
So, last year I started blogging again after a seven-year hiatus. I had started my first blog when I was first learning C# and .Net as a means of documenting my learning experience for the benefit of myself and others. I’d started it on Blogger, which was one of the bigger platforms at the time, and named it, appropriately, “Learning C# and .Net”. That effort lasted a year before family and work commitments eliminated available blogging time, and thus my blog languished while I continued to learn.
In the last post, I looked at Deconstructors in C# 7.0. I thought I’d create a library with a few extension methods to add Deconstructor support for Arrays and KeyValuePairs.
In my last post I had some fun with C# initialisers. This time we’ll look at Deconstructors that were introduced as part of the new ValueTuple support in C# 7.0. The code we’ll look at this time will probably be slightly more useful for real-world production code.