December 17, 2014

...Learn TDD with Codemanship

Implicit Contracts - A Simple Technique For Code Inspections

Just a quick bedtime note about a simple code inspection technique I use when the milk and cookies have been keeping me awake.

To cut a long story short, all executable code - from a function all the way down to a single expression - has a contract.

Take this little example:

If I wanted to do a bit of what we call "whitebox testing", and inspect this code for potential bugs, I could break it down into all the little executable chunks that make up the whole. (Not sure if a chunk of code is executable? Hint: could you extract it into its own method?)

For example, the first line:

If we think about it, this line of code has an input, and it has an output, just like a function. The input is the array called items, as it's declared earlier as a method parameter and only referenced here. The output is the string joinedItems, since it's declared and assigned to here, and referenced in code further down.

It also has pre- and post-conditions, just like a function. The array items must have at least one element for the code to work, otherwise we'll get an exception thrown when we try to reference the first element. And, provided there is at least one element in items, the post-condition is that joinedItems will be assigned the value of that first integer element as a string.

We can see already, by considering the contract implicit in this first line of code, that there may be a problem. What if items is empty? We must determine if that could ever happen during the correct functioning of the program as a whole. Could join() ever be called with an empty array as a result of valid user input or other software events?

Let's imagine it could happen, and we need to handle that scenario meaningfully. Perhaps we decide that our method should return an empty string when the array is empty. In which case, our code needs to change.

That's one potential bug. Using this technique, can you spot any more?

Posted 5 years, 7 months ago on December 17, 2014