DEV Community

David Cantrell
David Cantrell

Posted on

Coverage checks, conditions, and simplifying

In a recent comment on someone else's post I mumbled briefly about code coverage checks. I originally wrote the core of this post on there, but decided to break it out to an expanded post of its own because it was straying off topic.

I spend most of my coding time writing in perl, and I use Devel::Cover for my coverage checks. A feature of that tool which I particularly like, and which is lacking in some other tools, is that you don't just get to see which lines of code are covered, which branches taken and so on, you also get to see which conditions were exercised. "How does this differ from seeing which branches are covered?", you may ask. Consider this code:

if(foo() || bar()) {
    ...
}
Enter fullscreen mode Exit fullscreen mode

There's one branch, which can be either taken or not. Dead simple. However, there are three different conditions and if you don't hit them all Devel::Cover will tell you. Those conditions are:

  1. foo() is true (the value of bar() won't matter in all modern languages I'm familiar with)
  2. foo() is false and bar() is true
  3. foo() is false and bar() is false

If we expand the code a little:

if(foo() || bar()) {
    ...
} elsif(baz() && barf()) {
    ...
}
Enter fullscreen mode Exit fullscreen mode

We've now got 2 branches and 5 conditions:

  1. same as above
  2. same as above
  3. foo() is false, bar() is false, baz() is false (the value of barf() doesn't matter)
  4. foo() is false, bar() is false, baz() is true, barf() is false
  5. foo() is false, bar() is false, baz() is true, barf() is true

Obviously that's a trivial example, but when you have more complex conditionals they can hide surprising bugs. Your coverage checking tool may show you that all branches are tested, but unless you've also tested it with all possible conditions you don't know if it will always take the right branch!

It's at about that point that I realised I was straying waaaay off topic for a comment on the original post, for I was reminded of a Gresham College lecture on Hamilton and Boole, which includes an example of Boole's work applied by Claude Shannon to analysing and simplifying electrical circuits in his 1936 thesis "A Symbolic Analysis of Relay and Switching Circuits". Obviously, his work analysing the behaviour of a bunch of electrical switches in series and parallel can be applied to logical "switches" in code, thus helping you figure out exactly what the conditions are that you need to test if you are to get full coverage.

Top comments (0)