Klocwork - Get Started With A Static Code Analyzer

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

  1. Static Code Analysis detects the code smells, bad practices, and common errors before running the program.
  2. 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,
  1. Improves Product Quality
    • Minimize technical debts.
  2. 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.
  3. 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

  1. 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.

    Klocwork - Get Started With A Static Code Analyzer

    Klocwork - Get Started With A Static Code Analyzer

    Klocwork - Get Started With A Static Code Analyzer

  2. 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.

    Klocwork - Get Started With A Static Code Analyzer

Create a New Klocwork Project Via Portal


Klocwork - Get Started With A Static Code Analyzer
 
Klocwork - Get Started With A Static Code Analyzer
 
Klocwork - Get Started With A Static Code Analyzer
 

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.
  1. Write-Host "*************************Create New Klocwork Project************************";  
  2. $domain = Read-Host -Prompt "Enter Klocwork domain e.g. localhost";  
  3. $port = Read-Host -Prompt "Enter Klocwork Port e.g. 8080";  
  4. $projectname = Read-Host -Prompt "Enter Project Name e.g. My Project";  
  5. kwauth --url "http://${domain}:${port}" -v  
  6. kwadmin --url "http://${domain}:${port}" create-project $projectname;  
  7. start-process -FilePath 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'  
  8. -ArgumentList "http://${domain}:${port}/review/insight-review.html#views_goto:project=${projectname},view_id=1"  
  9. Write-Host "*************************End of Create New Klocwork Project******************";   
Output
 
Klocwork - Get Started With A Static Code Analyzer
 

Connect Your Visual Studio Solution to Klocwork Server

  • Open your project solution, right-click, and select "Klocwork Solution Properties."
    Klocwork - Get Started With A Static Code Analyzer
  • Select a Klocwork Server project

    Klocwork - Get Started With A Static Code Analyzer
Run the static analyzer of Klocwork with the MSBuild tool.
 
Code Sample
  1. using System;  
  2. namespace KlocWork.ConsoleSampleApplication  
  3. {  
  4.     public class Customer  
  5.     {  
  6.         /// <summary>  
  7.         /// Customer constructor we need to have an output saying   
  8.         /// 'This initializes the Customer class'  
  9.         /// </summary>  
  10.         public Customer()  
  11.         {  
  12.             Console.WriteLine("This initializes the Customer class");  
  13.         }  
  14.   
  15.         /// <summary>  
  16.         /// Detect CS.EMPTY.CATCH  
  17.         /// URL: http://localhost:8080/documentation/help/reference/cs.empty.catch.htm  
  18.         /// </summary>  
  19.         public string Order()  
  20.         {  
  21.             string result = string.Empty;  
  22.   
  23.             try  
  24.             {  
  25.                 if (sizeof(char) < 2)  
  26.                 {  
  27.   
  28.                 }  
  29.   
  30.                 switch (100 + 100)  
  31.                 {  
  32.                     case 200:  
  33.                         result = "200";  
  34.                         break;  
  35.   
  36.                 }  
  37.             }  
  38.             catch (Exception)  
  39.             { }  
  40.   
  41.             return result;  
  42.         }  
  43.   
  44.         /// <summary>  
  45.         /// Overrides Equals   
  46.         /// Detect CS.OVRD.EQUALS  
  47.         /// URL: http://localhost:8080/documentation/help/reference/cs.ovrd.equals.htm  
  48.         /// </summary>  
  49.         /// <param name="obj"></param>  
  50.         /// <returns></returns>  
  51.         public override bool Equals(object obj)  
  52.         {  
  53.             return true;  
  54.         }  
  55.     }  
  56.   
  57.     class Program  
  58.     {  
  59.         static void Main(string[] args)  
  60.         {  
  61.             var customer = new Customer();  
  62.             customer.Order();  
  63.   
  64.             Console.ReadLine();  
  65.         }  
  66.     }  
  67. }  
Before we integrate the command line of Klocwork with Visual Studio, see the step by step below to see the process involved.
  1. REM 1st step  
  2. REM build the C# solution project  
  3. kwcsprojparser msbuild <project-name>  
  4. REM 2nd step  
  5. REM this is optional but expect an .out file name after the build  
  6. type <project-name>.out  
  7. REM 3rd step  
  8. REM runs the integration build analysis  
  9. kwbuildproject --url http://localhost:8080/<project-name> --tables-directory <table_name> <project-name>.out  
  10. REM 4th step  
  11. REM loads the tables generated to the integration build server  
  12. kwadmin --url http://localhost:8080/ load <project-name> <table_name>  
To summarize the steps with the above code sample, see below,
  1. Build a C# project solution.
  2. This step is optional. Check the created .out file after the build.
  3. Run the integration build analysis of Klocwork
  4. 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.
  1. kwcsprojparser msbuild $(SolutionName)$(SolutionExt)  
  2. kwbuildproject  --url http://localhost:8080/new_project --tables-directory Klocworktable $(SolutionDir)\$(SolutionName).out --incremental  
  3. kwadmin --url http://localhost:8080/ load new_project Klocworktable  
See the sample code implemented in the Visual Studio build.
 
Klocwork - Get Started With A Static Code Analyzer
 
If you need some guidance on Macros, go to "Pre-build event/post-build event command line dialog box".
 
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.
 
Klocwork - Get Started With A Static Code Analyzer
 
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.
 
Klocwork - Get Started With A Static Code Analyzer
 
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.
 
Klocwork - Get Started With A Static Code Analyzer
 
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.
 
Klocwork - Get Started With A Static Code Analyzer
 
In our example, let us select #46 and see the details. 
 
Klocwork - Get Started With A Static Code Analyzer
 
Klocwork - Get Started With A Static Code Analyzer
 

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.


Similar Articles