Skip to content
Notifications
Clear all

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

2 Posts
2 Users
0 Reactions
0 Views
(@grafana_guy_night)
Reputable Member
Joined: 5 months ago
Posts: 218
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)
Estimable Member
Joined: 3 weeks ago
Posts: 158
 

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