Introduction
In the field of software development, software engineers have different approaches when solving a company problem. By practice, software engineers propose and discuss these different approaches and pick the best possible solution because it is impossible to implement everything in a given project. This practice takes time, especially if a project is still new, but this practice tends to decrease as the project matures.
This is why technical leads or similar technical positions create and update team coding standards that must be enforced across the entire team. Even small groups of software engineers nowadays have a standard way of dealing with day-to-day development at the early development stage.
A coding standard is vital because it can minimize shortcuts, continuous refactoring, inefficiencies, and messy codes. Moreover, many would argue that even a coding standard in place isn't enough because mistakes can still happen. These mistakes happen when the team is under pressure, there is a communication gap between colleagues, the need to deliver on time and sacrifice quality, automation tools are underused, insufficient testing, etc. That's why a team of software engineers needs a tool to help them. Thus, in this article, we'll discuss what static code analysis is, its benefits, and demonstrate its usage.
Disclaimer
I was provided with a free version in return for my honest review. All thoughts and opinions expressed herein are my own and not influenced by the developing company, and/or its affiliates, in any way.
Background
Within the scope of this article, we are going to focus on the usage of
Klocwork. We'll use Klocwork to diagnose a sample console application. And we'll be using the C# language, .NET Framework version 4.7.2, and Visual Studio 2019 Community Edition.
Lastly, this article assumes that you have Klocwork up and running within your environment (cloud, network, or local machine). However, if you haven't got the needed installer package to install Klocwork, you can go
here or, if you need an installation guide, you can go
here.
What Is Static Code Analysis?
The primary goal of static code analysis is to analyze code without running the code, facilitating higher quality software throughout the development process by having a set of rules or coding standards. Moreover, a static code analyzer varies significantly in scope and features. It can check for compiler level errors such as logical errors, coding styles, pre-configured coding standards to cloud-based suites of tools that cover even the complexity analysis.
In simple words, static code analysis helps us maintain a healthy codebase without debugging and running that code.
Common Questions About Static Code Analysis
- Is static code analysis and source code analysis the same?
- Yes, they are the same thing and used interchangeably.
- When can static code analysis be performed?
- Developers can perform this at the early stage of development before testing begins.
- As a software engineer, what are the suggested steps before checking-in your source code when using a static code analysis?
- Write the code.
- After writing the code, run the static code analyzer over your code changes.
- A static code analyzer will identify issues that need to be addressed to comply with your team's coding standards.
- Fix the issues that were reported by the tool.
- Move on to testing your source codes again, and if everything goes well, you can commit.
Note
These steps aren't set to stone and can be adjusted based on your team's processes and tools.
Static Code Analysis and Dynamic Code Analysis
- Static Code Analysis detects the code smells, bad practices, and common errors before running the program.
- Dynamic Code Analysis detects and examines the coding errors that may occur during or after a program has run.
Why Are Static Code Analyzers Useful?
Companies, of course, want to build a successful product for their target customers. Happy customers are equivalent to revenue for the company. Moreover, to provide a high-quality product requires effort, time, and budget. Hence, with the proper usage of a static code analyzer, a product team of software engineers can manage and minimize the acceptance of technical debt, bad codes, and bad practices.
Imagine minimizing these code issues at any stage of the development. It’ll mean higher chances of producing a high-quality product.
Here is a list of useful benefits of static code analyzers,
- Improves Product Quality
- Minimize technical debts.
- Improves Code Quality
- Minimizes and catches bugs early.
- Detects the codes that need to be simplified, which can lead to less refactoring.
- Improves communication between the dev team to produce high-quality code.
- Improves Code Review Process
- Most software engineers will eventually become a senior, lead, or architect in the future. As they get older with their craft, these engineers can quickly learn to analyze their own and some else code. But building software isn't just about coding, and our time is limited to read, teach, and guide someone else to code and code every feature there is. Enforcing these static code analyzers and integrating within the code review process will give more time to a more exciting and essential conversation rather than debating with small items in a pull request or code review.
Note
these benefits will eventually occur with proper management, proper usage of the tool, and an organized process.
How to Use a Static Code Analyzer?
Getting Started Using Klocwork Using C# Checker
In some cases, if you happen to install the Klocwork server on your device for testing purposes. Suppose your local device does have an antivirus installed in it. You can disable it in the meantime to make sure you can start the related services of Klocwork. Therefore, it is safer that you install Klocwork on a separate machine for dedicated use.
Prerequisites
- Klocwork Server version 20.3.0.5.1 (with proper and elevated permissions)
- Klocwork Command Line Tools for Windows version 20.3 (with proper and elevated permissions)
- Klocwork Visual Studio Plugin
- Visual Studio 2019 Community Edition
- Access to the project created in the Klocwork integration build server (e.g., http://localhost:8080/review/insight-review.html)
Starting the Klocwork Services
- Open your command line and type "kwservivce –projects-root <your project root> start". If any dialog comes out related to the windows firewall, you need to allow it. See the screenshots below.
- You can then go to your web portal of Klocwork Static Code Analysis by default with this URL: http://localhost:8080. See the login screen below.
Create a New Klocwork Project Via Portal
Create a New Klocwork Project Via Command Line
If ever you don't want to go to the step by step process, we have a sample PowerShell script that can automate the creation of the Klocwork project.
See PowerShell-script (create-new-klocwork-project.ps1) below. Just a note, the code below is a sample only, and you can change it according to your needs.
- Write-Host "*************************Create New Klocwork Project************************";
- $domain = Read-Host -Prompt "Enter Klocwork domain e.g. localhost";
- $port = Read-Host -Prompt "Enter Klocwork Port e.g. 8080";
- $projectname = Read-Host -Prompt "Enter Project Name e.g. My Project";
- kwauth --url "http://${domain}:${port}" -v
- kwadmin --url "http://${domain}:${port}" create-project $projectname;
- start-process -FilePath 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
- -ArgumentList "http://${domain}:${port}/review/insight-review.html#views_goto:project=${projectname},view_id=1"
- Write-Host "*************************End of Create New Klocwork Project******************";
Output
Connect Your Visual Studio Solution to Klocwork Server
Run the static analyzer of Klocwork with the MSBuild tool.
Code Sample
- using System;
- namespace KlocWork.ConsoleSampleApplication
- {
- public class Customer
- {
-
-
-
-
- public Customer()
- {
- Console.WriteLine("This initializes the Customer class");
- }
-
-
-
-
-
- public string Order()
- {
- string result = string.Empty;
-
- try
- {
- if (sizeof(char) < 2)
- {
-
- }
-
- switch (100 + 100)
- {
- case 200:
- result = "200";
- break;
-
- }
- }
- catch (Exception)
- { }
-
- return result;
- }
-
-
-
-
-
-
-
-
- public override bool Equals(object obj)
- {
- return true;
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- var customer = new Customer();
- customer.Order();
-
- Console.ReadLine();
- }
- }
- }
Before we integrate the command line of Klocwork with Visual Studio, see the step by step below to see the process involved.
- REM 1st step
- REM build the C
- kwcsprojparser msbuild <project-name>
- REM 2nd step
- REM this is optional but expect an .out file name after the build
- type <project-name>.out
- REM 3rd step
- REM runs the integration build analysis
- kwbuildproject --url http://localhost:8080/<project-name> --tables-directory <table_name> <project-name>.out
- REM 4th step
- REM loads the tables generated to the integration build server
- kwadmin --url http://localhost:8080/ load <project-name> <table_name>
To summarize the steps with the above code sample, see below,
- Build a C# project solution.
- This step is optional. Check the created .out file after the build.
- Run the integration build analysis of Klocwork
- Load the tables generated to the integration build server.
You can integrate the code sample above within your build process inside Visual Studio 2019.
Go to your startup project and go to properties. Go to "Build Events". At the Pre-build event, put the needed macros to replace the hardcoded values for Klocwork integration to work.
See the code below.
- kwcsprojparser msbuild $(SolutionName)$(SolutionExt)
- kwbuildproject --url http://localhost:8080/new_project --tables-directory Klocworktable $(SolutionDir)\$(SolutionName).out --incremental
- kwadmin --url http://localhost:8080/ load new_project Klocworktable
See the sample code implemented in the Visual Studio build.
One great thing about the Klocwork static analyzer is once you have integrated it into your environment (in our case Visual Studio). It can guide and tell you it has found an issue.
See the screenshot below.
You can then fix your code and try to build again until the issues are gone.
Klocwork Project Issue State Reports
Suppose you have been dealing with a lot of coding with your project. But there are times; we need to see the history of our issues detected by Klocwork. Within the Klocwork portal, we can see a graph about the issue states of our builds. However, these indicators are read-only that trace an issue's history from when it is first detected.
See the screenshot below.
As you can see at the bottom of the screenshot, there are three labels: existing, fixed, and new.
Here are the things we need to remember about these legends,
- New – these are the issues that were first detected
- Fixed – these are the issues that existed in the previous build but not in the current build.
- Existing – detected in both the current and previous build.
As a developer, we need to monitor builds when dealing with our project's issues. By comparing two builds, we can see what changes occurred between two builds. For example, the image build_6 shows the fixed and existing issues in the current build. Moreover, software engineers usually tend to compare their current build with a recent product-release build.
Within the portal, if in case developers need to differentiate two builds. For example, we can type "diff:build_6,build_7" in the search box and compare the two. After the page's right-hand renders new information, you'll see the different results.
Lastly, selecting a specific issue can be seen in full details that point directly towards your code.
In our example, let us select #46 and see the details.
Summary
In this article, we have seen the theoretical concepts of a static code analyzer. Moreover, we even answered some common questions about static code analysis, the types of code analysis and its types, and its benefits. Lastly, we have seen we have to get started with a static code analyzer by using the Klocwork tools. We have begun with Klocwork by running its services, creating a project via portal and PowerShell script, integration builds with Visual Studio, and navigating within the issue state reports using the portal.