From Good to Great Code: A Journey to Software Quality

Daffa Muhammad Faizan
11 min readApr 2, 2024

--

Programming is very straight-forward. It is a practice that is meant to achieve a specific goal by using code in an objective manner. However, the process or methodologies in achieving this goal is subjective. There is no one right way to code and the process of creating a software product is left to the developer to utilize his or her creativity. However, it is not ideal to let developers do as they please. Certain metrics are needed in order to assess the code on whether or not it has conformed to the needs of the user. We must realize that oftentimes in real life, the goal of programming is to develop software intended to be used by users. Therefore, one must compare their code to the requirements of the users and determine to what degree has the code met the needs of the users. Quality, an inherently subjective measure, is a perfect metric to determine this.

In this article, we’ll examine what I believe to be the most important attributes that make your code high quality, alongside a tool you can utilize to measure code quality.

Functionality

This attribute measures how much your code adheres with the requirements and the needs of the users. The most simplest measure to determine whether or not this attribute is fulfilled is by asking one simple question; is it working as intended?

Efficiency & Performance

Similar to functionality, this measures how much your code adheres with the time specifications. In this fast paced era, it is of utmost importance to avoid the inconvenience of waiting for a feature to load. Thus, it is important to keep efficiency in mind when it comes to developing a product. Your application must successfully run various tasks in a time limit.

Usability & Reliability

As the name suggests, this attribute measures how consistent your product is given various circumstances, environments, and tests. It is important from the user’s point of view that the product they’re using is failure free. Ideally, your product must run on different operating systems, browsers, and other environments.

Security

Lastly, this is what I believe to be one of if not the most important attribute in determining the quality of your code. Attacks are becoming more common as technology progresses and exploits must not come from your negligence or ignorance of your code. Simple features such as authorization and authentication must not be brushed aside and information or important data that is used in your application must be encrypted or at least put in an .env file.

SonarQube

To simplify your workflow, SonarQube is available as an open-source tool designed specifically to assess and improve code quality. It is designed for conducting thorough automated assessments of code quality by analyzing the code to identify any bugs, potential code issues, and security risks across a variety of programming languages. One thing that I like about SonarQube is its capability to enforce coding standards and best practices.

I’ll guide you through setting up SonarQube for your own organization while also setting up SonarQube for my team’s project!

Installing Docker

Different operating systems require different methods of installations. If you’re machine has a MacOS operating system and you’re utilizing homebrew to manage your packages, open your terminal and run:

brew install docker

If you’re on a Windows operating system or a MacOS without homebrew, please follow the official docker documentation provided below to install:

To check whether or not docker has been successfully installed on your system, open your terminal and run:

docker --version

Installing SonarQube as a Docker Container

Start by running your terminal and running these commands to install SonarQube as a container in docker:

On MacOS, run:

sudo docker run -d --name sonar --restart always -p 9000:9000 sonarqube:lts-community

On Windows, run:

docker run -d --name sonar --restart always -p 9000:9000 sonarqube:lts-community

Now, to check whether or not SonarQube has been successfully ran in docker on your local machine, open your terminal and run:

docker ps -a
Ensure that the “STATUS” is Up indicating that the conatiner is running.

SonarQube should be running and you can access it by opening your browser and navigate to your local machine’s IP address and the 9000 port. For example, if you’ve deployed SonarQube on your local machine, run:

http://localhost:9000/

Or, if you’ve deployed SonarQube on a VM, use the VM’s public IP Address like so:

http://44.207.134.71:9000/

Fulfilling Prerequisites

Before setting up SonarQube, there are a few prerequisites to fulfill. You’ll need to create a GitHub App to give SonarQube certain permissions for it to scan your repositories. To do this, follow these steps:

  1. Click your profile picture icon on the top right of your screen and click “Your organizations”.
  2. To the right of your organization, click “Settings”.
  3. After that, scroll down, expand “Developer settings”, and click “GitHub Apps”.
  4. Now, click “New GitHub App

Specify the following general settings in your app:

  • GitHub App Name: Your app’s name.
  • Homepage URL: You can use any URL, such as https://www.sonarqube.org/.
  • User authorization callback URL: Your instance’s base URL. For example, http://sonarqube.yourcompany.com. Note that for this to work, your SonarQube instance must be accessible through a public URL.
  • Webhook URL: To improve security, webhooks, by default, are not allowed to point to the SonarQube server since version 8.9LTS, therefore we recommend that you disable the feature. Unless you want to enable code scanning alerts for security vulnerabilities in GitHub, you should clear the Webhook Active checkbox to silence a forthcoming deprecation warning, and clear the Webhook URL and Webhook secret fields when creating your GitHub App.

Grant access for the following Repository permissions:

  • Checks — Read & write
  • GitHub Enterprise: Repository metadata — Read Only
  • GitHub.com: Metadata — Read-only
  • Pull Requests — Read & write

For private repositories, grant access to the following Repository permissions:

  • Contents — Read-only

If setting up GitHub Authentication, in addition to the aforementioned Repository permissions, grant access for the following Account permissions:

  • Email addresses — Read-only

And grant access for the following Organization permissions:

  • Members — Read-only
  • Projects — Read-only

Under “Where can this GitHub App be installed?,” select Any account. Finally, click “Create GitHub App”.

To see your GitHub App, follow these steps:

  1. Click your profile picture icon on the top right of your screen and click “Your organizations”.
  2. To the right of your organization, click “Settings”.
  3. After that, scroll down, under “Third-party Access” click “GitHub Apps”.
  4. Click “Configure” on the app you just created.
  5. Now, click “App settings” with the gear icon near the top of the page.

You’ll need a Client Secret and a Private Key. You can generate them in this page. Please take note of the GitHub App ID, Client ID, Client Secret, and Private Key. It’ll be used later.

Setting up SonarQube

When you first access SonarQube, you’ll be prompted with a login page. Use the username and password: admin and admin, respectively:

Username: admin & Password: admin

Now, you’ll be prompted to create your own password. After you’ve finished, click “Update”.

For the sake of this example, we’ll be analyzing a project from GitHub. So for that, click the GitHub icon:

SonarQube will require us to create a configuration of the projects we want to analyze. This will allow SonarQube to have certain permissions and do code analysis on the repositories, like I mentioned earlier. I’ll guide you through the process.

First of all, fill the Configuration name with anything you please. Next, fill the GitHub API URL with https://github.company.com/api/v3 if you’re using GitHub Enterprise. Otherwise, use https://api.github.com. Lastly, fill in the rest of the fields with the credentials (GitHub App ID, Client ID, Private Key) you’ve taken note of when creating your GitHub App. You can leave the “Webhook Secret” field blank.

After you’ve done configuring, click “Save configuration”. You’ll be redirected to the final step of the setup involving the creation of two files in your project; “sonar-project.properties” and “build.yml”.

Because the contents of these files differ from one another, I’ll let you do this on your own while following the instructions given by SonarQube. After you’re done, push the changes to your remote repository and you should see that SonarQube successfully analyzed your project!

Analyzing Results

To be frank, analyzing your code can sometimes be complex. But, I’ll be guiding you through how to analyze your project by explaining to you how me and my team analyzed our own project! First off, you can see the analyzed projects on the Projects tab on SonarQube.

The issues discovered in a project can fall into categories such as Bug, Vulnerability, Code Smell, Coverage, or Duplication, each with its corresponding number or percentage. Additionally, these issues can be classified by severity: blocker, critical, major, minor, or info.

The Issues tab consistently shows the category, severity level, tag(s), and estimated effort required to resolve each issue. Users can assign issues to others, add comments, and adjust severity levels directly from this tab. Clicking on a specific issue provides further details about it.

Moving on, we can open the Quality Gate section of your project. A Quality Gate establishes criteria a project must meet before it’s deemed ready for production release, essentially answering the question of whether the code can be pushed to production in its current state.

As you can see, there are already a few criterias pre-defined by SonarQube. New Bugs indicating any bugs on the recent analysis, new vulnerabilities which is self explanatory, new security hotspots, and the easiest row to fix; the maintainability row. You can see the code debt and also the code smells there.

Clicking on one of the criterias brings you into the Measures tab. Here, you can precisely see which files and what part of the code corresponds to the issue that is being flagged by SonarQube. Practical isn’t it?

Reliability

The reliability of a system is mainly judged by its bug count. Factors like issue complexity, quantity, status, type, and severity help assess reliability and estimate the effort needed for improvements.

  • Bugs — Number of bug issues.
  • New Bugs — Number of new bug issues.
  • Reliability Rating — A-E, depending on the presence of minor, major, critical, or blocker bugs.
  • Reliability remediation effort — Effort to fix all bug issues. The measure is stored in minutes in the DB. An 8-hour day is assumed when values are shown in days.
  • Reliability remediation effort on new code — Same as Reliability remediation effort but on the code changed in the New Code period.

Security

This code aspect deals with identifying security weaknesses through vulnerability issues. It includes estimating the effort required to fix these vulnerabilities and determining the security rating based on their severity.

  • Vulnerabilities — Number of vulnerability issues.
  • Vulnerabilities on new code — Number of new vulnerability issues.
  • Security Rating — A-E, depending on the presence of minor, major, critical, or blocker vulnerabilities.
  • Security remediation effort — Effort to fix all vulnerability issues. The measure is stored in minutes in the DB. An 8-hour day is assumed when values are shown in days.
  • Security remediation effort on new code — Same as Security remediation effort but on the code changed in the New Code period.
  • Security Hotspots — Number of Security Hotspots.
  • Security Hotspots on new code — Number of new Security Hotspots in new code.
  • Security Review Rating — A letter grade based on the percentage of Reviewed (Fixed or Safe) Security Hotspots.
  • Security Review Rating on new code — The same for new code.
  • Security Hotspots Reviewed — Percentage of Reviewed (Fixed or Safe) Security Hotspots.
  • New Security Hotspots Reviewed — Percentage of Reviewed (Fixed or Safe) Security Hotspots for new code.

Maintainability

Maintainability of code is judged by factors like code smells, technical debt, and bug issues. Code smells indicate design or readability weaknesses, while technical debt measures the effort needed to fix these issues. The technical debt ratio compares development cost to fixing cost. Bug issues and their reliability ratings also impact maintainability, with effort estimates needed for resolution. Ultimately, maintainability involves addressing these factors to ensure software longevity.Code Smells — Total count of Code Smell issues.

  • New Code Smells — Total count of Code Smell issues raised for the first time in the New Code period.
  • Maintainability Rating — This (SQALE) rating given to the project is related to the value of Technical Debt Ratio.
  • Technical Debt — Effort to fix all Code Smells. The measure is stored in minutes in the database. An 8-hour day is assumed when values are shown in days.
  • Technical Debt on New Code — Effort to fix all Code Smells raised for the first time in the New Code period.
  • Technical Debt Ratio — Ratio between the cost to develop the software and the cost to fix it, based on the time cost of the issues and the estimate of the time to write the given number of lines of code.
  • Technical Debt Ratio on New Code — Ratio between the cost to develop the code changed in the New Code period and the cost of the issues linked to it.

How did SonarQube benefit my project?

After using and experiencing using SonarQube for our project, there are a few things myself and my team gained benefit from:

  1. Increase Skills
    SonarQube helped our team improve our skills by providing regular quality feedback and enhancing code transparency.
  2. Raise Quality
    By identifying code standard violations, SonarQube help aided us in bug eradication, ensuring high-quality coding standards. Its dashboard enable focused monitoring of code quality and issue tracking.
  3. Vulnerability Detection
    SonarQube detects security vulnerabilities like injection flaws and cross-site scripting in code, enhancing overall software security.

Fin.

In conclusion, these guidelines of code quality ensure that software not only performs its intended functions but does so reliably, efficiently, and safely across various environments. Embracing tools like SonarQube enables developers to closely follow these attributes by providing a framework for analyzing and ultimately improving code quality. This not only benefits the developers but ultimately serves the end-users by delivering robust, efficient, and secure software solutions. In software development, tools like SonarQube are handy allies in guiding developers to meet and exceed the standards of software quality.

References:

https://wiki.geant.org/display/GSD/SonarQube+Metrics#:~:text=linked%20to%20it.-,Reliability,Bugs%20%E2%80%93%20Number%20of%20bug%20issues.

--

--