Friday, August 17, 2018

TDD in an Economically Sensible Way

On TDD, we're often at two extremes: At the start of a project, we're as idealistic as many TDD authors would have us do - writing tests for almost everything. Then, as deadlines near, we drop TDD altogether, and then deliver a product with ticking production-issue time bombs.

The right attitude be somewhere in the middle: Apply TDD in an economically sensible way, so that you can sustain it consistently throughout the project.

Two questions are important:

  1. What is the chance this scenario will have bugs?
  2. How critical is this scenario?

#1: What is the chance this scenario will have bugs?

Obviously, we shouldn't test things so simple as getters/setters, null-checks, is-positive-number-checks, etc. If a one-second inspection of the code in question reassures you that it works, you probably don't need a test for it.

You can actually *increase* the amount of code that falls into this category. How? By using well-trusted third-party libraries. For example, instead of writing your own regex, check if the methods in Apache Lang 3 StringUtils will do the trick.

This is why I don't favor minimum code-coverage standards. More tests doesn't mean better quality. In fact, you get better quality if you increase the amount of code that is so simple that it doesn't need tests at all.

#2: How critical is this scenario?

Let's use university enlistment as an example.

Say, there's a rule where the student may not enlist in two sections with the same subject. There's a bit of complexity in implementing this rule, but not all that much. It doesn't fall into the category of 1-second-inspection; maybe it will take around 30 seconds to read through the code to verify if it works. Looks like we should write a test for this, right?

However, how many times would a student be silly enough to enlist in two sections with the same subject? And wouldn't the student notice if he does? And what is the consequence to the school? Not much - they end up billing the student for two sections, which can be corrected later.

On the other hand, check the scenario of cancellation of an enlistment. This is very easy to implement, it could actually fall into the 1-second-inspection category. However, the consequences of a failed cancellation process can be serious for the school - they'll have a lot of complaints from students and parents, they'll have to make a lot of accounting adjustments. So even if cancellation is very easy, it still merits a test.

No comments:

Post a Comment