Code smell: Arrowhead code
A tip for recognising a common code smell is to look for arrowheads. Consider the following python code:
if condition1:
if condition2:
if condition3:
# Code block 1
else:
# Code block 2
else:
# Code block 3
else:
# Code block 4
The code looks like the head of an arrow. The else blocks are hard to read and reason about in the example. It is not clear what code block is the main case and which is protections. In order to understand the logic you have to switch between reading the ifs at the top and the code blocks at the bottom. This makes the reading of this funtionality weird.
The code can be easily improved using guards. Guards work by using early return to simplify the flow:
if not condition1:
# Code block 4
return
if not condition2:
# Code block 3
return
if not condition3:
# Code block 2
return
# Code block 1
This flattened version of the code is much easier to read and reason about. You can take it one if statement at a time, and it is easier to identify that Code block 1 is the main code block.
Looking for arrows in the code can help identify cases of unnecessary nesting. Code smells are usually hard to recognise instantly. Especially after having spend a long time writing and reasoning about a new piece of code. By looking for arrows in the code it can make it easier to identify code smells that would not otherwise be obvious to the writer.
Last updated: 2025-04-20