Railroad tracks crossing multiple times

Complexity in code can be of two types. The domain has complexity that has to be represented in the code. On top of that we add complexity that is related to our solution. Sometimes this is called inherent and accidental complexity.

Conditionals, like if- and switch-statements, can be used to model complexity. When we encounter a conditional in the code we should stop and consider:

Is this conditional a part of the domain, or created by how we implemented the solution?

To me, a true conditional is related to the domain. The rest, like error handling, is also important, but should be isolated.

The guard clause pattern can be used for this. It uses early return and can be used to check for invalid input. The “true” conditionals can then work with a known state and the rest of the function will focus on the domain.

At a larger scale than a function, the guard clause pattern turns into a border around the domain code. An example of this is hexagonal design, or ports and adapters. The input is happening on the border, also dealing with validation. So the domain logic can expect a valid state.
Inside the hexagon we have domain code that can be written as pure functions (or the object oriented equivalent). When passing the result on, we let the border deal with the messy reality outside our bubble, like retrying when a POST request times out.

Separating the domain logic from uncertainty caused by our dependencies and architecture is also useful when testing. Tests needed for the domain should be roughly the same independent of what technology we use. The test cases we need for the architecture are often related to our language and framework. External dependencies, like talking to the database, should be kept out of unit tests entirely. Mixing the different testing areas makes it harder to spot when things get unnecessarily complicated. I am all for the design pressure aspect of unit tests.

So, is this conditional something you would use when explaining the domain to someone, or a result of how it is implemented?

This text was last modified 2024-02-16

Related texts

A single frosted leaf with clear contours and veins.

TDD in the context of writing code to be read

Wunder Baum hanging from a car window (Known as Little Trees in most English-speaking countries)

Wunderbaum testing