7 Metrics to Evaluate your code quality using static analysis
Published: 2023-02-20 19:23:08



Have you ever wondered how to measure the quality of your code using meaningful metrics? One of the popular measures used across teams is "Code Coverage", It's a great measure that provides a lot of insights, but it's not enough, especially when multiple teams or even many developers are working on the same code base, which is a very common situation when working on a monolithic application. In this post, I will share with you 7 useful metrics that you can use to get a pulse on the quality of your code, as well as a quick demonstration with [SonarQube](https://www.sonarsource.com/products/sonarqube/) on how to generate these metrics.

### [1. Code complexity](#code-complexity)

Writing, debugging, and maintaining code is a complicated process in and of itself, and it can become even more complicated as the project scope expands and changes over time. High code complexity comes at a high cost in terms of severe bugs and defects.

Many factors can contribute to code complexity and make it difficult to maintain, such as the number of nested conditions within the code, such as `for`, `if/else`, `switch`, `while`, and so on. If you want to learn more about complexity, read more about it [here](https://www.sonarsource.com/docs/CognitiveComplexity.pdf).

I found this article useful about explaining code complexity as well, [a-simple-understanding-of-code-complexity](https://www.codegrip.tech/productivity/a-simple-understanding-of-code-complexity/).

### [2. Code coverage](#code-coverage)

Code coverage is a metric shows the percentage of code executed during testing. It aims to help you understand how much of your code is being tested. It's an important metric that can help you assess the quality of your code, deliver features with confidence that you didn't break anything that used to work, and write a testable, decoupled code.

I could go on and on about the advantages of writing tests for the rest of this post. If you haven't tested your code yet, you should start now. It may take a little longer to develop a feature, but it will definitely save you time later when you're adding new features or updating existing ones.

The question now is how much of my code should be covered by test cases. It's debatable whether you should test 100% or not; I believe if you can do so, you should because it gives you peace of mind later on, though it's difficult to maintain 100% at all times. If you can't reach 100% at least test the parts of your code if they fail your application will breakdown and might lead to losing customers.

### [3. Bug density](#bug-density)

Bug density is the number of known bugs per number of lines of code. It's another metric that can help you improve the quality of your software. Most of the teams are using thousand lines of code as benchmark in the previous definition.

Defects can be detected before releasing on productions in many ways, mostly with writing tests for your code, effective code reviews or manual/automated QA. Even though some defects can escape to production, using static analysis tools can help you avoid these defects reaching your end user.

### [4. Duplicated code](#duplicated-code)

Duplication usually occurs when multiple developers are working on different parts of the same application at the same time. Since they’re working on different tasks, they may be unaware their colleague has already written similar code that could be repurposed for their own needs.

There’s also more subtle duplication, when specific parts of code look different but actually perform the same job. This kind of duplication can be hard to find and fix.

Again, static analysis can help you detecting the first type of duplication and give you some insights to fix it and improve your code quality and make it less smelly.

### [5. Code maintainability](#code-maintainability)

The ease of modification and maintainability of code is measured by code maintainability. It can be measured by how long it takes to make a change and the risk that the change will break something.

In other words, it refers to the Technical Debt in your application. The less there is, the better. Static analytics will provide you with details about the Code Smells in your application as well as the amount of Debt.

### [6. Coding standards](#coding-standards)

Compliance to coding standards is one measure that a static analysis does not provide, but I believe it contributes to the quality of your code.

We all write code in our own unique way. Working in a team and having different developers contribute to the same codebase without some predefined coding standards in place will result in a chaotic mess and poor quality code. For instance, using camel case vs. snake case with variables and classes, using spaces vs. tabs, formatting, and so on. Every programming language has its own standards, which you should enforce within your team to improve quality and make the code look consistent regardless of who wrote it.

### [7. Security vulnerabilities](#security-vulnerablities)

Detecting security risks in code is an important metric to keep an eye on. It could be secrets/passwords that are hard coded in your code or a third-party package that has a vulnerability and must be updated to get the latest security patch fixed. Static code analysis tools can easily detect such issues; [guardrails](https://www.guardrails.io/) is a popular tool that specialises in this, I highly recommend integrate it with Github or any other version control repository you are using to run with every new code pushed.

### [Demo with SonarQube](#demo-with-sonarqube)

One of the market leading tools that helps with measuring code quality when it comes to static analysis is [SonarQube](https://www.sonarsource.com/products/sonarqube/), I will show you a quick demo of what it can do for you.

I will be using it with [PHP](https://www.php.net/) and [Laravel](https://laravel.com/) project.

#### Installation

There are many ways to install SonarQube and get it up and running, I will be using brew and docker in this demo, I will leave the installation reference [here](https://docs.sonarqube.org/latest/setup-and-upgrade/install-the-server/) and find out what works for you.

Make sure [Docker](https://www.docker.com/) is installed and running and no services are running on port `9000`.

##### From your terminal run:

```
docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latest

```

You should now have SonarQube server up and running on port `9000`.

##### In your browser open `http://localhost:9000/` and you should see a login page.

##### Enter the default username and password

- username: admin
- password: admin

set a new password and you should land on create your project page.

##### On create your project page I choose manual setup for the purpose of the demo but feel free to choose any other available option.

![create your project page](https://res.cloudinary.com/dt5qg3orv/image/upload/c_scale,q_auto:good,w_1400/v1676828713/Screenshot_2023-02-19_at_8.02.20_PM_ei4cj4.png)

##### Fill the project details and go to the next page.

![Fill the project details page](https://res.cloudinary.com/dt5qg3orv/image/upload/c_scale,q_auto:good,w_1400/v1676828713/Screenshot_2023-02-19_at_8.02.57_PM_enubeh.png)

##### On how do you want to analyze your repository, choose locally.

![how do you want to analyze your repository](https://res.cloudinary.com/dt5qg3orv/image/upload/c_scale,w_1400/v1676828713/Screenshot_2023-02-19_at_8.03.06_PM_npr24d.png)

##### Generate a token for your project.

![Generate a token for your project](https://res.cloudinary.com/dt5qg3orv/image/upload/c_scale,q_auto:good,w_1400/v1676828713/Screenshot_2023-02-19_at_8.03.15_PM_jru5iv.png)

##### you will be asked what option best describes your build? in my case I will choose PHP and MacOs.

![what option best describes your build?](https://res.cloudinary.com/dt5qg3orv/image/upload/c_scale,w_1400/v1676828713/Screenshot_2023-02-19_at_8.09.28_PM_k31smw.png)

##### You should be provided with code to run in your project to get the code analysis.

##### Before you do make sure sonarScanner is installed on your machine, find all installation options here [SonarScanner Installation](https://docs.sonarqube.org/9.9/analyzing-source-code/scanners/sonarscanner/)

If you're using MacOs run:

`brew install sonar-scanner`

##### Once installed navigate to your project dir and run the following command:

`sonar-scanner \                                                                       
  -Dsonar.projectKey={ProjectName} \
  -Dsonar.sources=. \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.login={ProjectKey}`

you should get an EXECUTION SUCCESS message if everything runs successfully.

##### Navigate to the browser again and you should be able to view the metrics for your project similar to the images below

![SonarQube analysis result 1](https://res.cloudinary.com/dt5qg3orv/image/upload/c_scale,q_auto:eco,w_1400/v1676829337/Screenshot_2023-02-19_at_9.55.04_PM_dw7qax.png)

* * *

![SonarQube analysis result 2](https://res.cloudinary.com/dt5qg3orv/image/upload/c_scale,q_auto:good,w_1400/v1676829337/Screenshot_2023-02-19_at_9.55.18_PM_oqfhaa.png)

There is much more than that there, have a look and see all of the useful insights it gives you to improve your code quality.

I would highly recommend including such analysis in your CD/CD pipelines if not all but at least code coverage and security vulnerabilities scanning, it will help you to maintain your code quality within your team.

### [Conclusion](#conclusion)

These metrics provide insight into the code quality, helping to identify areas of improvement, enforce coding standards, and minimize the risk of bugs or security vulnerabilities.

That was one way to improve your code quality, but it is not the only way. According to a [Smart Bear](https://smartbear.com/) 2020 [Code Review survey](https://static1.smartbear.co/smartbearbrand/media/pdf/the-2020-state-of-code-review.pdf), the number one way a company can improve code quality is through **Code Review**.

And I would finish with a quote from [Peter Drucker](https://en.wikipedia.org/wiki/Peter_Drucker)

> <mark>If you can't measure it, you can't improve it.</mark>

Which is true most of the time.

Thank you for taking the time to read this; I hope you found it useful. Please contact me if you require additional assistance or have any suggestions.