javaspringunit-testingmaintainabilitycode-maintainability

Does keeping cyclomatic complexity between 5-10 makes unit testing easier?


I'm planning to keep track of cyclomatic complexity for method and classes in between 5-10. Will it be easier to write unit tests if we keep it in that range? Does it help us write effective unit tests which can be valuable in long run?

I know unit tests can be written properly without tracking cyclomatic complexity.

Any thoughts?


Solution

  • Yes, because cyclomatic complexity does nothing else than counting the number of decisions in a function.

    The more decisions you have the more branches you have to consider in your tests. Also keeping the cyclomatic complexity low will help you build software which has a higher maintainability because it more or less forces you to develop your function to be more atomic. Take this example:

    You could either write one unit test which covers the following function with all its 3 possible branches:

    foo(a, b, c) {
      if (a) {
        if (b && c) {
          return 1;
        }
        return 2;
      }
      return 3;
    }
    

    or you could split it up like this:

    foo(a, b, c) {
      if (a) {
        return foo2(b, c);
      }
      return 3;
    }
    
    foo2(b, c) {
      if (b && c) {
        return 1;
      }
      return 2;
    }
    

    write two unit tests, one for function foo2(b,c) and if you write the unit test for function foo(a,b,c) you do not care about the correctness of foo2(b,c) anymore because you already tested it.

    Long story short: cyclomatic complexity will not only increase testability but furthermore it will increase maintainability and readability of your code as well as other non-functional requirements.