IntermediateLesson 3

Static Code Analysis

ELI5 Explanation

Static analysis reads your code without running it — like a senior engineer doing a very thorough code review, every single time, on every line, in seconds.

Technical Explanation

SonarQube performs static analysis by parsing source code into an Abstract Syntax Tree (AST), then running rule patterns against it. It does not execute the code. Analysis covers:

SonarScanner sends analysis results to the SonarQube server, where rules from the active Quality Profile are applied and issues are stored.

Tip: Run SonarScanner as part of build — not after packaging. It needs source files and optionally compiled bytecode for deeper analysis (Java, C#).

Visual

Source Files
Parse to AST
Apply Rules
Issues Reported

Hands-on Commands

Scan with coverage report
# Java project with Jacoco coverage
mvn clean verify
mvn sonar:sonar \
  -Dsonar.projectKey=my-app \
  -Dsonar.host.url=http://sonarqube.company.com \
  -Dsonar.login=$SONAR_TOKEN \
  -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml

# JavaScript project
sonar-scanner \
  -Dsonar.projectKey=frontend-app \
  -Dsonar.sources=src \
  -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info \
  -Dsonar.host.url=http://sonarqube.company.com \
  -Dsonar.login=$SONAR_TOKEN

Debugging Scenario

Scan runs successfully but coverage shows 0%. Root cause: test reports were generated in a different folder than declared. Fix by aligning sonar.coverage.jacoco.xmlReportPaths (or equivalent) to where test tooling actually writes reports. Always verify with ls target/site/jacoco/ before running sonar step.

Interview Questions

Beginner

  • What is static analysis?
  • Does SonarQube run your code?
  • What is an AST?
  • Why run analysis on pull requests?
  • What files does SonarScanner analyze?

Intermediate

  • How does incremental analysis differ from full scan?
  • How does SonarQube integrate test coverage data?
  • What happens if compiled classes are missing for Java analysis?
  • How do exclusions affect scan scope?
  • How do you scan a monorepo with multiple projects?

Scenario-based

  • Scan reports show no issues on a complex project. What is suspicious?
  • Analysis is slow and times out in CI. What optimizations help?
  • New developer sees hundreds of existing issues. How do you manage noise?
  • Branch scan misses a vulnerability seen in main. Why might this happen?
  • You need file-level analysis exclusions for generated code. How?

Real-world Use Case

A payments team enabled branch analysis so every PR showed the delta of new issues only, reducing noise from legacy backlog and helping reviewers focus on changes introduced in the current work.

Summary

Static analysis provides instant, consistent code review at scale without running the application. Next lesson explains the three categories of issues SonarQube surfaces.