Sitemap

Static Code Analysis

9 min readMay 7, 2025

In fast-moving software projects, it is tempting to prioritize delivery over maintainability. Yet from my experience, writing code that runs is only the first step. True progress comes when we ensure that code remains readable, secure, and resilient over time.

This is where Quality Assurance (QA) and Static Code Analysis play a key role. These practices help surface issues early, enforce consistency, and reduce the long-term cost of changes.

In this post, I’ll reflect on how static analysis and QA have shaped our work on SiNgawas, and how tools like SonarQube and CI/CD integration can significantly improve product quality without slowing development down.

What is Static Code Analysis?

Static code analysis is a technique for reviewing source code without running the program. Its main purpose is to catch potential issues such as bugs, security risks, or poor coding practices before they make it to production.

Unlike testing, which checks behavior during execution, static analysis focuses on the structure of the code itself. It helps detect things like unreachable code, duplicated logic, unused variables, or risky patterns that could lead to future problems.

In SiNgawas, static analysis has proven valuable. It has pointed out edge cases we missed, warning about overly complex functions, and encouraged more consistent code across the team. Over time, this kind of early feedback made code reviews more focused and reduced the number of last-minute fixes.

In our project, we adopted SonarQube to help maintain backend code quality as the codebase grew. It scans our source code for bugs, code smells, and security vulnerabilities, and provides detailed reports integrated directly into our development workflow. This allows us to catch issues early ensuring that each commit meets a baseline level of quality.

What is Quality Assurance (QA)?

Quality Assurance (QA) is a broader discipline that ensures software meets a defined standard of quality before it is released. While static analysis is one tool within this process, QA also includes activities like automated testing, manual testing, code reviews, and continuous monitoring.

The goal of QA is not just to find bugs, but to prevent them. We want to be confident that the software behaves as expected, performs reliably, and is safe to use. In practice, QA is applied throughout the entire development cycle. From planning and design, to development, testing, and even post-release feedback, all of this involves QA.

In our project SiNgawas, QA plays a central role in backend development. We run unit and integration tests on every merge request to catch functional errors early and use SonarQube to enforce static code.

Post-deployment, we integrate Sentry to monitor runtime exceptions. This helps us catch issues that pass through test coverage or only appear under specific real-world conditions. The insights from Sentry often guide our follow-up patches and improve future iterations.

QA is ultimately about protecting both users and developers. It gives us confidence to ship faster without sacrificing quality and helps us sustain long-term reliability as the project evolves.

Static Analysis and QA

Static code analysis is a foundational part of Quality Assurance (QA). While QA encompasses many activitie, from writing tests to monitoring applications, static analysis provides an automated, consistent way to assess code before it is executed. It acts as an early warning system, surfacing potential issues that might otherwise go unnoticed until runtime or production.

By integrating SonarQube into our CI pipeline, we established clear quality gates. If the analysis detects a blocker or critical issue, the pipeline fails — and that feedback reaches the developer before a reviewer even looks at the code. This reduces review friction and raises the overall standard of contributions.

What Can SonarQube Actually Do?

SonarQube has been mentioned several times already in this post, but what exactly does it do?

At its core, SonarQube is a static code analysis platform that helps teams write cleaner, safer, and more maintainable code. It automatically scans your source code, identifies issues, and provides structured feedback, all without having to run the application.

In SiNgawas, we use the Community Edition of SonarQube, which already includes most of the essential features needed for backend QA

Key Features of SonarQube

  • Bug Detection
    Finds logic errors, null dereferences, and other problematic patterns in your code that could lead to runtime bugs.
  • Code Smells
    Flags maintainability issues, such as overly complex methods, duplicate logic, or deeply nested conditions.
  • Security Vulnerabilities
    Identifies potentially insecure code (e.g., hardcoded secrets, SQL injection risks, etc.).
  • Cognitive Complexity Analysis
    Measures how difficult your code is to understand, helping you refactor for better readability.
  • Duplication Detection
    Highlights sections of code that are copy-pasted across files or modules.
Press enter or click to view image in full size
Overview in sonarqube

One of the best things about SonarQube is how quickly we can assess the health of our codebase. For example, in the screenshot below, we can instantly see that:

  • All quality gates passed
  • No new issues were introduced
  • Test coverage is at 100% (with a threshold of ≥80%)
  • Code duplication is 0%
  • No unresolved security hotspots

These metrics give us immediate feedback. If anything falls below our set thresholds, the pipeline fails, and the merge cannot proceed. This reinforces a healthy development culture where code quality is checked automatically and continuously.

SonarQube makes static analysis actionable. It doesn’t just highlight problems, it guides you toward a cleaner codebase.

Typical QA Flow

Quality Assurance is not a single step. It is a continuous process that runs throughout the development cycle. In backend projects like SiNgawas, we follow a structured QA flow that helps us identify issues early, address them efficiently, and maintain long-term code quality.

Here is what our QA process usually looks like:

1. Issue Identification

The process begins by identifying potential problems as early as possible. We use SonarQube to scan every commit for code smells, complexity, and vulnerabilities. At the same time, unit and integration tests run automatically to catch functional or logical errors.

Too much cognitive complexity in one function

After pushing to Gitlab, the pipeline ran as usual. SonarQube analysis returned a warning, pointing out a list of maintainability issues, including this one. This allowed us to address the problem before the code was merged.

2. Issue Diagnosis

Once an issue is detected, we investigate the cause. SonarQube highlights the affected lines of code and provides explanations, making it easier to understand what needs to be fixed. For test failures, we trace the flow to determine whether the issue comes from logic, data handling, or interaction between components.

For example, we need to reduce the former function’s Cognitive Complexity from 46 to the 15 allowed.

3. Fix and Refactor

After diagnosing the issue, we apply a fix. This may involve rewriting logic, simplifying a complex method, or addressing a security concern. We aim not only to solve the problem but also to improve code maintainability.

Get Puti Raissa’s stories in your inbox

Join Medium for free to get updates from this writer.

For example, to reduce the cognitive complexity, we make helper functions

def determine_status_from_lamaran(sesi):
if hasattr(sesi, 'user_lamaran') and sesi.user_lamaran:
lamaran = sesi.user_lamaran[0]
if lamaran.status == 'DITERIMA':
return 'Mengawas'
elif lamaran.status == 'MELAMAR':
return 'Terdaftar'
return 'Dibuka'

def determine_status_from_roles(sesi, current_status):
if current_status == 'Mengawas':
return current_status

for ujian in getattr(sesi, 'prefetched_ujians', []):
for role in getattr(ujian, 'user_roles', []):
for rr in getattr(role, 'user_role_ruangans', []):
if rr.status_plotting == 'FINAL':
return 'Mengawas'
elif rr.status_plotting == 'PENEMPATAN' and current_status == 'Dibuka':
return 'Menunggu'
return current_status

4. Re-validation

The revised code is then re-analyzed. Tests must pass, and SonarQube must report no new critical or blocker issues. This step helps ensure the fix is effective and does not introduce new problems.

5. Merge and Monitor

Once the code meets quality criteria, it is merged into the main branch. After deployment, we continue monitoring using Sentry, which alerts us to runtime exceptions or unexpected behavior. These reports often reveal edge cases that escaped test coverage and help us refine our QA strategy.

This QA flow is part of every code change. By combining automated tools with team practices, we maintain a reliable backend even as the system evolves.

Setting Up SonarQube in Real Projects (GitLab CI/CD)

After understanding what SonarQube can do, the next step is integrating it into your actual workflow. In SiNgawas, we use SonarQube Community Edition, hosted internally by Fasilkom UI, and connected directly to our GitLab CI/CD pipeline.

1. Create a Project on SonarQube CSUI

First, we created a new project on SonarQube CSUI and selected GitLab integration. After completing the setup, we received three key values:

  • SONAR_HOST_URL – the URL of the SonarQube instance
  • SONAR_TOKEN – the authentication token
  • sonar.projectKey – the unique project identifier

We stored the first two as environment variables in GitLab, and used the sonar.projectKey in our project’s configuration.

2. Add sonar-project.properties

In the root directory of our backend project, we added a sonar-project.properties file. This file tells SonarQube how to analyze the project:

sonar.projectKey=Singawas-BE
sonar.sources=.
sonar.exclusions=**/tests/**, **/migrations/**, **/venv/**, **/env/**, manage.py, **/__init__.py, **/settings*.py
sonar.python.coverage.reportPaths=coverage.xml

This configuration defines what to scan (sources), what to ignore (exclusions), and where to find the test coverage report generated by pytest.

3. Configure .gitlab-ci.yml

We then updated our GitLab CI to include two relevant jobs: one for testing and one for SonarQube analysis.

Unit Testing Stage

Runs Django tests and outputs the coverage report.

test-django:
image: $IMAGE_PYTHON
stage: test
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: always
- if: '$CI_COMMIT_BRANCH'
when: always
before_script:
- apt-get update
- apt-get install -y libpq-dev gcc python3-dev
- source env/bin/activate
dependencies:
- build-django
script:
- pytest --cov=. --cov-report=xml
artifacts:
paths:
- coverage.xml

SonarQube Analysis Stage

Uses sonar-scanner to analyze the codebase and enforce the quality gate.

sonarqube:
image:
name: sonarsource/sonar-scanner-cli:11
entrypoint: [""]
stage: sonar
cache:
key: "sonar-cache-$CI_COMMIT_REF_SLUG"
paths:
- "${SONAR_USER_HOME}/cache"
- sonar-scanner/
dependencies:
- test-django
script:
- ls -al
- sonar-scanner -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.login=$SONAR_TOKEN -Dsonar.python.coverage.reportPaths=coverage.xml -Dsonar.qualitygate.wait=true
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
- if: $CI_COMMIT_BRANCH == 'main'
- if: $CI_COMMIT_BRANCH == 'development'
- if: $CI_COMMIT_BRANCH == 'staging'
- if: $CI_COMMIT_BRANCH == 'ci-cd'
- if: $CI_COMMIT_BRANCH =~ /^dev-.*/
- if: $CI_COMMIT_BRANCH =~ /^pbi-\d+-\w+/

Note: Avoid using allow_failure: true. This ensures that if SonarQube detects a critical issue or the quality gate fails, the pipeline is blocked, enforcing quality consistently.

Further Static Analysis: Beyond the Basics

Once basic static analysis is in place, there are several ways to deepen its impact. In SiNgawas, after integrating SonarQube and meeting our initial quality gates, we explored how to evolve our use of static analysis into a more proactive quality strategy.

1. Defining Custom Quality Gates

Instead of relying solely on default thresholds like “no blocker issues,” we can define custom rules that better reflect our project’s goals. For example:

  • Require test coverage of new code to stay above 90%
  • Keep duplicated code below 3%
  • Prevent any new code smells on key branches

This encourages developers to maintain quality from the start, rather than fixing problems after review.

2. Tuning the Rule Set for Backend Needs

SonarQube comes with a large rule set, but not all rules are relevant for every backend project. We can tailor the configuration by:

  • Disabling rules that produce false positives or clash with our conventions
  • Enabling stricter rules around complexity, exception handling, and data access

This makes the feedback more aligned with the project’s technical needs.

3. Merge Request Decoration

With the right integration, SonarQube can display code quality issues directly in merge requests. This means developers don’t need to leave GitLab to act on feedback, making the review cycle faster and more focused.

In SiNgawas, this helped reduce back-and-forth in code reviews, since SonarQube handled many repetitive checks automatically.

4. Tracking Trends Over Time

SonarQube also provides historical data. We can track:

  • Test coverage progress over time
  • Changes in code duplication or complexity
  • Modules with growing technical debt

These trends help guide technical decisions and long-term refactoring plans, especially in larger projects.

--

--