Wednesday, September 9, 2015

Making Data Relationships Obvious

When you are writing tests you end up using literals or hand-constructed data objects.

However, using literals can obscure the meaning a little. Not horribly; most people can puzzle them out quickly enough, but you can make it easier on the reader.

In most of these tests, the values are pretty much arbitrary, but the relationship between the values is essential. For instance, when checking that no bonus is given when sales is less than quota, I could state that sales is 10,000.00 and that the quota is 9,900.00.  Pretty much anyone could tell that the quota is less than sales here, right?

But what if we made it really explicit?

     double quota = 10000;
     double sales = quota - 100;

This is how I like to roll. For instance, in python:

     event_date = datetime(2015,9,10)
     later = event_date + timedelta(days=10)
     earlier = event_date - timedelta(days=2)

And how about this alternative when you want to construct an object as a slight variation as another of the same type?

     origin = datetime(2015,9,10)
     later = datetime(origin.year, origin.month,

I think that building one object as a modification of another (by add/subtract/etc, or by unpacking one into the constructor of the other) makes the intention of the author clear.

Of course, if you modify the original object, the object constructed through relationship instead of literal will change with it. 

The easier maintenance is just a bonus you get for being an expressive programmer.