Our Code Is Too Complex To Test

Learn how complex code can be hard to test due to accidental complexity, uncontrolled external systems, or code entanglement.

Complex code

Professional developers routinely deal with highly complex code. That’s just a fact of life. It leads to one valid objection: our code is too difficult to write unit tests for. The code we work on might be highly valuable, trusted legacy code that brings in significant top-line revenue. This code may be complex. But is it too complex to test? Is it true to say that every piece of complex code simply cannot be tested?

Understanding the causes of untestable code

The answer lies in the three ways that code becomes complex and hard to test:

  • Accidental complexity: We chose a hard way over a simpler way by accident.

  • External systems cannot be controlled to set up for our tests.

  • The code is so entangled that we no longer understand it.

Accidental complexity

Accidental complexity makes code hard to read and hard to test. The best way to think about this is to know that any given problem has many valid solutions. Say we want to add a total of five numbers. We could write a loop. We could create five concurrent tasks that take each number, then report that number to another concurrent task that computes the total. We could have a complex design pattern-based system that has each number trigger an observer, which places each one in a collection, which triggers an observer to add to the total, which triggers an observer every 10 seconds after the last input. Yes, we know some of those are silly. we just made them up. But let’s be honest—what kinds of silly designs have we worked on before? we know we have written code that was more complex than it needed to be.

Get hands-on with 1200+ tech skills courses.