Order Doesn't Matter

I took over a project from another developer this week who was let go. I'd like to use some of his coding mistakes as an example of what not to do. He wasn't necessarily let go because of these mistakes, but you should avoid them anyways.

There is a unit test project in the solution, which is great, but some of the tests are bad. Check out these asserts:

Assert.AreEqual(4, charges.Count);
Assert.AreEqual("HAND13", charges.First().PCAT);
Assert.AreEqual("HAND01", charges.Last().PCAT);
Assert.AreEqual(decimal.Parse("472.5"), decimal.Parse(charges.First().Total));
Assert.AreEqual(decimal.Parse("1350"), decimal.Parse(charges.Last().Total));

Besides the decimal.Parse("472.5") (LOL), what else is wrong here?

charges.First() and charges.Last()

Why? Because order doesn't matter! Nowhere in the logic or use cases does it say that the order of charges is important. When you go out to dinner, does the order of items on the receipt matter? Not really. It's the same case here, except the developer did not recognize this and is expecting a certain item to be First and another to be Last. This is bad!

I found this bug when trying to make an optimization. There was a foreach loop I wanted to squeeze some performance out of. This loop adds items to the charges collection. I changed the loop to use Parallel.ForEach (because order doesn't matter). When I did this it broke the unit test because the expected First and Last items were not where they were expected to be. I changed the tests to read:

Assert.AreEqual(2, charges.Count(x => x.PCAT == "HAND13"));
Assert.AreEqual(2, charges.Count(x => x.PCAT == "HAND01"));
Assert.AreEqual(472.5m, decimal.Parse(charges.First(x => x.PCAT == "HAND13").Total));
Assert.AreEqual(1350m, decimal.Parse(charges.First(x => x.PCAT == "HAND01").Total));

I am still using First but with some context to single out a specific item. This is much better, and now my Parallel.ForEach can be used.

Cast Hacking

Have you ever wanted to cast a base class into a subclass? Consider these two classes:

public class Animal { }
public class Dog : Animal { }

Because of the inheritance we can create an Animal from a Dog because we know that Dog has all of the necessary properties to set on Animal. Quick example:

var dog = new Dog();
var animal = (Animal) dog;

This works in .NET. But what if you wanted to create a Dog from an Animal? I mean, a dog is an animal, right? Unfortunately Dog may have some properties that Animal doesn't and so you will get an exception at runtime when trying to cast from an Animal to a Dog:

var animal = new Animal();
var dog = (Dog) animal;

Causes this runtime exception:

An unhandled exception of type 'System.InvalidCastException' occurred.
Additional information: Unable to cast object of type 'Animal' to type 'Dog'.

Getting around this casting issue means you would have to create a new Animal, then for every property on Animal set the value to the corresponding property on Dog. What pain. Who has time for that? What happens when you add a new property to Animal - will you remember to update this property-copying code as well? It wasn't intended specifically for getting around casting issues but for property copying Automapper is awesome. It does pretty much what you would expect. It maps the properties of one class to another so you don't have a boring and messy slop of code to maintain. Here is how you can create an Animal from a Dog using Automapper:

Mapper.CreateMap<Animal, Dog>();
var animal = new Animal();
var dog = Mapper.Map<Animal, Dog>(animal);

For the properties of Dog that Animal doesn't have, if the property is a value type it's value will be the type's default value and for reference types the value will be null.

Thats it. Go forth and break all of the traditional coding rules you know!

Generate an enum from SQL server database table

I have a lookup table in SQL Server and a corresponding enum in my code - two different sources that represent the same thing. The problem I was having was that one would become out of sync with the other. To solve this I created a T4 template that will generate an enum based on database values. The database becomes the master source and I just have to run the T4 template to update my code... easy!

Here is the T4 template I created if you would like to use it as well. It generates the enum in C#. The enum name is determined by the name of the .tt file so if you want an enum named LanguageType then rename the .tt file to "LanguageType.tt". Customize the variables at the top of the script with your connection string, table name, and the columns used for the enum member name and value.

EnumGenerator.zip [2KB]

Linq.js CRUD Methods

One of my favorite JavaScript libraries is Linq.js (LINQ for JavaScript). Unfortunately the author is not responding to pull requests so I'm going to post my update here.

I've added CRUD methods to the library so that you can Add, Delete, and Update items easily. I've found this very useful pattern where I load a lot of data when the page loads, convert it to an Enumerable using Linq.js, then as the user modifies data update it locally and send updates back to the server asynchronously.

Here are examples of each method I've added:

var data = Enumerable.From([
    { "id": 1, "url": "http://amazon.com", "title": "Amazon" },
    { "id": 2, "url": "http://google.com", "title" : "Google" },
    { "id": 3, "url": "http://yahoo.com", "title" : "Wrong" }

data.Add({ "id": 4, "url": "http://msn.com", "title" : "MSN" });

data.Delete(function(x) { return x.id == 1; });

data.Update(function(x) { return x.id == 3 }, { "id": 3, "url": "http://yahoo.com", "title" : "Yahoo!" });

You can download my linq.js file here. You can also play with a fiddle I created using the example above.

Alternatively you can pass a function to Update instead of an object (makes sense if you are updating more than one item at a time):
data.Update(function(x) { return x; }, function(x) {
    x.title = "updated " + x.id;
    return x;

Trick for debugging parallel code

Thanks to Microsoft's TPL (Task Parallel Library) writing parallel applications has become easy. In some cases it's as easy as swapping a foreach loop for a Parallel.ForEach loop. The one thing that it makes harder though is debugging! How are you supposed to keep track of which thread you are in? When stepping through code the debugger jumps around to different lines because multiple threads are running code at the same time. It's frustrating. Here is a simple solution I found by only letting one thread run at a time while debugging. Use ParallelOptions and a debug preprocessor! Example:

var items = new[] {1, 2, 3};
var options = new ParallelOptions();

options.MaxDegreeOfParallelism = 1;

Parallel.ForEach(items, options, item =>
    //do something

The best part is you don't have to change anything when you do a release build. The preprocessor takes care of not compiling line 5 and so the default MaxDegreeOfParallelism value will be used in production.