What a year of SonarQube warnings taught me about my own code
A static analyser does not make code good. It makes you look at the code you stopped looking at.
For about a year, the only automated check on our API was a SonarQube scan in the CI pipeline. No test project, no other analysis gate. Every push went through the scanner, and every few weeks I would open the dashboard, sigh, and start a "code optimized (sonarQube)" branch.
Looking back across the history, I count roughly two dozen distinct cleanup passes on the API and a handful on the Next.js portals. Some were trivial. A few found real bugs. One made the code worse. This note is about all three kinds, because the lessons are in the mix.
The hotspot that was a real injection
The first time SonarQube earned its keep was a security hotspot in a helper that loaded e-mail templates. The code built a stored-procedure call by string interpolation:
// Before
var sql = $"EXEC sp_GetEmailTemplate @EmailCode = N'{emailType}'";
var template = _db.EmailTemplates.FromSqlRaw(sql).AsEnumerable().FirstOrDefault();
The value came from our own code, not from a user, so it "could not" be exploited. That is exactly the kind of reasoning that stops being true six months later when someone wires the parameter to a request. The fix was to pass a real SqlParameter through our shared stored-procedure helper. As a bonus, the method stopped blocking a thread: .AsEnumerable().FirstOrDefault() on a raw query is synchronous, and it became a proper async call.
// After
var template = (await _sp.QueryAsync<EmailTemplate>("sp_GetEmailTemplate",
new SqlParameter("@EmailCode", emailType))).FirstOrDefault();
Duplication is a bug factory
The biggest single cleanup was a duplication warning across fourteen service files. Every "create comment" method (on documents, requirements, certifications) had its own copy of the same block: upload the attached files to blob storage, queue a background job for each, build a DataTable of the results, and call a stored procedure.
Copy-pasted code is not just untidy. When one copy gets a fix, the others do not. Pulling the block into three helpers (ProcessFiles, ExecuteCommentStoredProcedureAsync, AddBackgroundJobIds) took one service from several hundred lines to under half that, and the next time we needed to change how attachments are stored, it was one change instead of six.
A later pass removed a net 635 lines across 26 files. I did not add a single feature in that commit. It is still one of the commits I am proudest of.
Regular expressions with a timeout
SonarQube flagged several regular expressions as vulnerable to catastrophic backtracking (ReDoS): a crafted input can make the engine try billions of paths and pin a CPU core. On the API, the fix in modern .NET is pleasant:
static partial class Patterns
{
[GeneratedRegex("[A-Z]", RegexOptions.None, matchTimeoutMilliseconds: 1000)]
public static partial Regex Upper();
}
The source generator compiles the pattern at build time, and the timeout means a hostile input fails after one second instead of hanging the request. On the front end, where JavaScript has no timeout, the fix was to bound every repetition: [^"]* became [^"]{0,500}. Unbounded quantifiers on user input are now something I notice the moment I read them.
Cognitive complexity is a readability score, and it is right
Some controller actions had grown into walls of nested ifs: update a customer, add a comment, assign a participant. SonarQube's cognitive-complexity rule scored them far over the limit, and it was right. I could not explain those methods to a colleague without scrolling.
Pulling each branch into a named helper made the main method read like a list of steps. Reworking methods with more than seven parameters forced me to notice which of them belonged together. And while doing it I found an unused impersonaterId query parameter, with a comment next to it warning that it could be abused to act as another account. Nobody would have found it in the noise of a 200-line method. Simplifying the code is how it surfaced.
The small ones add up
- Pass the cancellation token. Our error-handling middleware wrote its JSON response without
context.RequestAborted. Passing it means work stops when the client has already gone. - Use real randomness for IDs. Tab and session IDs on the front end were built with
Math.random().toString(36). They becamecrypto.randomUUID(), which also drops a deprecatedsubstr. - Constants for repeated strings,
ControllerBaseinstead ofControllerfor API-only controllers, no nested ternaries, nocatchblocks that only rethrow.
None of these is exciting alone. Together they are the difference between a codebase that feels looked after and one that does not.
The fix that made it worse
Not every cleanup was an improvement. To clear an "unused variable" warning, one pass changed catch (Exception ex) to catch (Exception), and then, to clear "unused field", deleted the injected logger. The warnings went away. So did every log line for those errors. Exceptions were now swallowed in silence.
The warning was pointing at a real problem: the exception was caught and never logged. The right fix was to use ex, not to delete it. In the same spirit, explanatory comments were once stripped from a component because a rule complained about "commented-out code", which only means code that has been commented out, not prose.
A warning is a question, not an instruction. If the fix makes the warning disappear but does not answer the question, it is not a fix.
What static analysis never saw
The same codebase that passed its SonarQube scan with zero security issues later produced about 80 findings in a manual OWASP audit, five of them critical. Almost all of them were access-control bugs: an endpoint that trusted an ID from the request, a stored procedure that never asked who was calling. A scanner cannot know that customer A must not read customer B's documents. Only someone who understands the business can.
The slowest endpoint we ever had was not flagged either. The "all documents" page checked whether each file existed in blob storage, synchronously, one request per row, with a page size of 100. Taking the status from data we already had, and defaulting to ten rows per page, turned a slow page into an instant one. That was a profiling problem, not a linting problem.
What replaced it
In the end we removed SonarQube from the pipeline and replaced it with a quality gate of our own: unit tests, lint, security tests, a build and an environment check on every pull request. That is not a judgement on the tool. It is a recognition that a scan run in bulk every few weeks is a cleanup routine, not a safety net. Tests that fail before merge change behaviour. Dashboards that are read occasionally do not.
- Gate the pull request on new issues only, from the first week, instead of fixing a backlog in waves.
- Never fix a warning by deleting the thing it points at. Read the rule first.
- Treat static analysis as one input. Pair it with tests and an occasional human review aimed at what tools cannot see: authorization and business rules.