Friday, September 14, 2012

Clarity over Cleverness: Follow Up, and a Practical Example


I had a nice discussion with a coworker about my last post, and wanted to add some clarity: specifically, the topic was about a piece of unit test code that looked something like this:

        public class UnitTestHere()
        {
                ...
                Db.CreateThing();
                ...
        }

        public static int CreateThing(this IDbCommand command,
                Action<Thing> modifier = null)
        {
            var thing = new Thing
                                    {
                                        ...
                                    };

            if (modifier != null)
            {
                modifier(thing);
            }

            command.Insert(thing);

            return (int) command.GetLastInsertId();
        }

So that, to modify the default values for the 'Thing' in the unit test, users had to do this:

        public class UnitTestHere()
        {
                ...
                Db.CreateThing(t =>
                        t.someField = someNonDefaultValue);
                ...
        }

My argument was along the lines of 'I don't want to have to do this to write my unit test'.

To which I got the reply (very correctly, I might add) that if I don't know it, then I should use it as a learning opportunity. Which is very true. In my case, the argument was less that I didn't know it and more that I felt the delegate was fancy-clever-overkill.

In this case, the code is both clever and clear - it serves a valid purpose, allows people reading the unit tests to see very obviously what values are being set IN the test, and it's dynamic enough to handle changes to any and all value changes in the inserted 'Thing' that might come up in future tests (like the one I was writing that brought about this discussion, for example). The hurdle of writing it is pretty quickly solved, and once the code is there it is clear enough to be maintained / changed with little effort.

I never meant to imply that more advanced tools don't have a place, just that sometimes people use them when they may not be better than the more basic options available to them.

And with that, I'm dropping this one. Happy Coding!

No comments:

Post a Comment