I'm looking to configure my Continuous Integration/Continuous Deployment pipeline to log a warning whenever there's an excessive amount of nested if statements in the code. As a test, I started with a rule for just two nested ifs, like this:
```
- id: python-too-many-nested-ifs
languages: [python]
severity: WARNING
message: |
Excessive nesting of if statements.
patterns:
- pattern-inside: |
if $A:
...
- pattern-inside: |
if $B:
...
- pattern: |
if $C:
...
```
However, this seems to trigger on single if statements as well. Is it feasible to set up semgrep to accurately detect excessive nesting of if statements?
3 Answers
Plenty of static analysis tools come with configurable complexity warnings. It might be worth looking into whether semgrep offers that kind of flexibility.
I’m not super familiar with semgrep, but if you’re trying to manage nesting, keep an eye on cyclomatic complexity. It's a key metric that helps to gauge the complexity of your code. This is often a good angle to approach your issue from.
You might want to think about the potential downsides of enforcing such a rule. If you clamp down too hard on nested ifs, you could inadvertently force developers to write more complicated single if statements, which can actually hurt readability.

Exactly! Cyclomatic complexity is a big deal. It can really spiral out of control with too many nested conditions, making tests harder to implement. By the way, while many developers have mixed feelings about case statements, they can offer a clearer alternative to having so many nested ifs.