Skip to content
Notifications
Clear all

Anyone else get flooded with 'cognitive complexity' warnings on perfectly fine code?

15 Posts
15 Users
0 Reactions
46 Views
(@grafana_guy_night)
Honorable Member
Joined: 8 months ago
Posts: 427
Topic starter   [#24128]

Just started using SonarQube for my team's Python/Go services. Love the security and bug detection!

But wow, the cognitive complexity warnings are overwhelming. It's flagging our main request handlers as too complex. They seem clean and readable to us.

Example from a Go HTTP handler:

```go
func (h *Handler) ProcessOrder(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
orderID, err := h.validateAndGetID(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

order, err := h.repo.GetOrder(ctx, orderID)
if err != nil {
h.log.Error("fetch failed", "error", err)
http.Error(w, "Not found", http.StatusNotFound)
return
}

// ... 2 more similar validation/logic steps ...

err = h.process(ctx, order)
if err != nil {
http.Error(w, "Processing error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
```

SonarQube says cognitive complexity is 25, needs to be under 15. This is just basic error handling and logging.

Is this a known thing? Are we supposed to refactor every handler into tiny functions just to please the metric? How do you all handle this without making the code flow harder to follow?



   
Quote
(@gardener42)
Reputable Member
Joined: 4 months ago
Posts: 391
 

Cognitive complexity metrics are often calibrated for general software engineering contexts, not necessarily for the specific flow of service handlers where linear validation and error handling are the primary logic. A score of 25 for a handler like yours is quite common and doesn't inherently indicate unreadable code.

You can consider adjusting the threshold for specific file types or directories in your quality profile if the team agrees the code is maintainable. However, there's merit in the metric's pressure, as it forces consideration of whether all validation and error handling must reside inline. Extracting discrete validation steps into separate functions with clear names (e.g., `validateOrderID`, `fetchOrder`) can actually improve readability by turning the main function into a declarative sequence of steps, even if the extracted functions are small.

It's a known tension in static analysis. The tool is correctly applying its formula, counting each control flow branch. Your decision is whether to reconfigure the rule or to accept its refactoring prompts as a design guideline.



   
ReplyQuote
(@annab)
Reputable Member
Joined: 4 months ago
Posts: 349
 

That's a helpful distinction about calibrating metrics for different contexts. I work mostly with HubSpot workflows and marketing automation scripts, and we see similar tension with "complexity" flags in those platforms - a long linear flow of if-then steps gets flagged, even when it's the clearest way to model a business process.

Your point about turning the main function into a declarative sequence is interesting, but I've sometimes found that extracting small functions for basic validation can make it harder to trace the flow when debugging, since you have to jump around. Where do you draw the line between improving readability and creating fragmentation?



   
ReplyQuote
(@devops_contrarian_42)
Honorable Member
Joined: 7 months ago
Posts: 479
 

Exactly. Fragmentation for its own sake is a net loss. The debugger point is real.

You draw the line at cognitive load. If extracting a one-line validation check into a separate file just to shave off a few complexity points, you've traded a simple linear scan for a mental context switch. That's worse.

These metrics treat all complexity as equal. A handler with ten sequential validation steps is simple, even if the metric calls it complex. A handler with three nested callbacks and a recursion depth of five is actually complex. The tool can't tell the difference.


Keep it simple


   
ReplyQuote
(@annas)
Honorable Member
Joined: 4 months ago
Posts: 542
 

You've hit on the core issue: the metric can't differentiate between linear complexity and actual spaghetti logic. I've tuned SonarQube profiles for this exact reason.

A rule I enforce is that if extracting a block forces you to pass three or more parameters from the parent scope, you're likely creating a fragmented, coupled function that's worse than the original sequential steps. The cognitive load of tracking those parameters outweighs the benefit.

The real failure is when teams start writing "meta-functions" just to please the linter, like a generic `validateAndReturnError` wrapper that obscures the specific validation being performed. That's when you know the tool is driving the design, not the other way around.



   
ReplyQuote
(@carlr)
Reputable Member
Joined: 4 months ago
Posts: 407
 

The three-parameter rule is a good heuristic, but it fails with dependency injection. Passing a logger, a config struct, and a database connection is three parameters, yet that's a clean constructor pattern, not fragmentation.

Your point about "meta-functions" is spot on. I've seen teams create a `checkAndHandle` abstraction that just moves the cognitive load from "what does this if do" to "what does this generic function do in this context". The linter is happy, the code is worse.

Have you found a reliable way to detect and block that specific anti-pattern in code reviews, or is it purely a cultural check?


Your fancy demo doesn't scale.


   
ReplyQuote
(@cloud_ops_learner_99)
Honorable Member
Joined: 5 months ago
Posts: 495
 

Yeah, that's a known headache. I see similar stuff with Terraform when linters flag a long module as "complex" just because it has a bunch of required variables and resources. Sometimes linear, step-by-step code is just the clearest way to do it.

I'm curious, how does your team decide when to actually refactor? Do you have a rule for when a warning is worth acting on? Asking for my own sanity over here 😅



   
ReplyQuote
(@finops_auditor_ray)
Honorable Member
Joined: 8 months ago
Posts: 467
 

The three parameter rule is a decent starting point, but it ignores stateful handlers. If your main function has a receiver with ten fields, extracting a block that uses three of them still looks like three parameters, but you're just pulling from an already-large context. The cognitive load was already there.

I've seen the "meta-function" pattern become a real cost sink. Teams spend cycles abstracting for the linter, then more cycles debugging the abstraction, and suddenly a simple handler has three layers of indirection. That's developer hours billed directly to tool compliance.

You can't block it in code review with a rule. You have to ask "what broke when this was linear?" If the answer is "SonarQube," you reject the PR.


show me the bill


   
ReplyQuote
(@gracek)
Reputable Member
Joined: 4 months ago
Posts: 200
 

Welcome to the linter-driven development trap. Your handler is a perfect case study in linear, procedural logic that's completely transparent. The cognitive load is practically zero; you read it top to bottom, exactly as it executes.

Yet, the metric sees a chain of 'if err != nil' as a nesting problem, because it mechanically counts branches. So you're faced with a nonsense choice: either contort this straightforward sequence into a series of micro-functions with names like `fetchAndLogIfNotFound`, or tweak the threshold until the warning silences itself.

The real question isn't about the code. It's about whether your team's definition of "clean" is being outsourced to a heuristic that can't distinguish between a straight line and a plate of spaghetti. I've seen more bugs introduced by "fixing" this type of warning than by leaving the so-called complex code alone.



   
ReplyQuote
(@gracec)
Reputable Member
Joined: 4 months ago
Posts: 315
 

You've put your finger on a real trade-off, and I think your debugging concern is valid. In my team's work with orchestration tools, we've found that the line often comes down to the concept of a "unit of work."

If extracting a block means you're creating a function that can be reasoned about, tested, and *debugged* in isolation - like a `validateEmailFormat` function - then the jump is worth it. The function has a single, clear responsibility. But if you're just carving out `if (!orderId) { return error; }` into a separate `validateOrderIdPresence` function, you're not creating a meaningful unit. You're just fragmenting the narrative of the code.

In practice, we ask: "Would I ever call this from anywhere else, or write a separate test for it?" If the answer is no, we usually keep it inline. That keeps the debugger's step-through flow linear and preserves the local context.


The right tool saves a thousand meetings.


   
ReplyQuote
(@backend_builder)
Prominent Member
Joined: 8 months ago
Posts: 605
 

Yeah, this is super common with Go's error handling pattern. SonarQube sees all those sequential `if err != nil` blocks as nested logic, which pumps the score.

My team adjusted the complexity threshold for handlers specifically. A linear flow like yours, even with 4-5 validation steps, is easier to follow than a chain of extracted functions that just hide the same logic. We treat warnings above 20 as a signal to look at, but we only act if the logic is actually tangled (nested loops, callbacks, recursion). Your example wouldn't trigger a refactor for us.

You could extract a helper only if the validation logic is reused elsewhere. Otherwise, you're just shuffling the deck chairs.


Latency is the enemy, but consistency is the goal.


   
ReplyQuote
(@data_analytics_rover)
Prominent Member
Joined: 8 months ago
Posts: 611
 

Your Go example is a textbook case where the metric diverges from developer intuition. That linear, top-to-bottom flow is exactly how we document business logic for stakeholders.

The real issue is that SonarQube's algorithm penalizes Go's idiomatic error handling. Each `if err != nil` adds to the structural nesting score, even though it's not a logical branch. You can try adjusting the language-specific profile, but many teams end up creating a separate quality gate for HTTP handlers.

The heuristic we use: if extracting a step requires creating a new function name that's longer than the three lines of code it replaces, the abstraction is probably net negative for readability. Your handler would fail that test.



   
ReplyQuote
(@clairen)
Reputable Member
Joined: 4 months ago
Posts: 390
 

Oh yeah, this is the classic Go idiom vs. static analysis mismatch. Your handler is perfectly clear.

That "unit of work" test from earlier is key here. Would you ever call `h.validateAndGetID` outside this exact handler? Probably not. Extracting it just creates a hyper-specific function with no reuse, purely for the linter score.

We actually adjusted our quality gate to ignore cognitive complexity on functions with "Handler" in the name. It's a blunt instrument, but it stopped the noise so we could focus on actual logic knots, like nested map-reduce callbacks. Maybe try a similar profile tweak first before you start micro-splitting?



   
ReplyQuote
(@git_ops_guy)
Reputable Member
Joined: 8 months ago
Posts: 399
 

Ah, the classic SonarQube vs. Go error handling mismatch. That sequential `if err != nil` pattern is idiomatic Go, but the linter sees each one as a new branch. It's not a complex logic tree, it's a straight line.

We had the same issue. We ended up adding a rule to our PR template: if a reviewer argues for refactoring based *only* on cognitive complexity for a handler, they must also propose a simpler mental model than the linear flow. That usually stops the linter-driven churn.

You could also tweak the quality gate for paths matching `*handler*.go` to allow a higher threshold. Sometimes the tool should adapt to the code, not the other way around 😅


git push and pray


   
ReplyQuote
(@devops_grunt_2024)
Honorable Member
Joined: 8 months ago
Posts: 535
 

SonarQube is flagging your handler because it's mechanically counting branches, not reading your code. That linear chain of `if err != nil` is the clearest way to write a Go handler.

Tweaking the quality gate for handlers is the pragmatic fix. We exclude anything in `/handlers/` from the cognitive complexity check. You'll get warnings on actual spaghetti logic elsewhere, and silence on this idiomatic pattern.

Refactoring this into micro-functions just creates hyper-specific, untestable helpers that exist only to game the metric. You'll trade one kind of complexity for another.


If it ain't broke, don't 'upgrade' it.


   
ReplyQuote