Two weeks ago, I started talking about automated unit testing. Last week, I talked about unit testing best practices. Today, I want to continue that theme but I want to make it much more concrete by explaining test driven development by example.
The example we will look at is a common component in most applications today – the lowly validator.
Let’s have a look at the requirements and design we’ll be implementing.
The type we will validate (Name) has two members – first and last. It gets used in several other types and is very important to our overall application.
Here’s a little UML to describe it:
The business rules we want to implement for the validator are pretty simple, but they’re more than enough for us to have a good example:
- Name.first is required
- Name.last is required
- If both Name.first and Name.last are invalid, both errors should be flagged in a single call to the validator.
In addition to the business rules, there are some technical goals we’d like to meet. Whereas the business rules came to us from someone on the business side, these we do just because it’s the right thing to do.
- Separate what is done from how it is done.
- Ensure that “Tell; Don’t Ask” is followed.
- Enable easy discovery of which fields have errors and what those errors are.
Separate What is Done From How it is Done
Separating what is done from how it is done has been a best practice going back decades. We’ll apply it in a couple of different ways.
First, we want to make sure we have a common handle for all validators, so we’ll create an interface.
We’ll also use apply this approach within methods so that algorithm is in one spot and implementation in another.
Tell; Don’t Ask
Sometimes you need to ask an object for its state. However, when you do that for the purpose of making some decision that is commonly made across your application, the behavior is usually better off being placed in the object itself.
This helps keep your code DRY and eases maintenance. Of course, these two help ensure your application behaves consistently.
Test Driven Development by Example Video
This is my first video tutorial ever. I can’t tell you how many times I recorded it and re-recorded it, but I can tell you that creating this gave me a greater appreciation of all the other folks out there that provide these types of examples.
I’ll do more in the future. After all, practice makes proficient – right?