PMD – Source code analyzer to find programming flaws

PMD has proved to be a useful tool for developers, whether working on a small project or development of an extensive system or software.

Writing code has never been an easy task. Most of the applications in the market have hundreds of lines of code. An example is one of the most popular games, Minecraft, which has at least 4,815,162,342 lines of code.

Maintaining this code and ensuring that it is sustainable is not an easy task. Luckily, we have several tools available to help you manage your source code. One of these tools is PMD.

PMD is an opensource code analyzer that checks for errors in your code and generates a report. It scans your source code and checks for issues and bugs like; dead code, empty statements, open curly braces, declared and unused variables, duplicated code, and naming issues. These are but a few examples.

Let’s take an example of the below sample java code below;

package fosslinux;
public class tuts {
    public static void main(String[] args) 
   { 
  // My Java Code
  System.out.println("Hello FossLinux"); 
  } 
}

By checking this code with PMD via the command line, we get the following output;

fosslinux/tuts/pmd-bin-6.21.0-full/pmd-bin-6.22.0-SNAPSHOT/bin/app.java:3:
All methods are static.
Consider using a utility class instead. 
Alternatively, you could add a private constructor or make the class abstract to silence this warning.
fosslinux/tuts/pmd-bin-6.21.0-full/pmd-bin-6.21.0-full/pmd-bin-6.22.0-SNAPSHOT/bin/app.java:3:
The class name 'app' doesn't match '[A-Z][a-zA-Z0-9]*'

As you can see in the above PMD report, there are several recommendations and warnings. That is the basic working of PMD.

Additionally, PMD comes with a Copy-Paste-Detector (CPD) utility. It detects duplicated code in various programming languages like; Java, Python, C, C++, Objective-C, PHP, Perl, Fortran, Go-Lang, Lua, Matlab, Javascript, Dart, JSP, and Swift. These are but a few examples. You can read more about the supported languages on their official GitHub page Here.

The abbreviation PMD is just but a backronym and is not defined. However, some of the commonly used abbreviations include; “Programming Mistake Detector” and “Programming Mess Detector.” The tool itself is, however, referred only as PMD with the tagline, “Don’t Shoot The Messenger.” Below is the official PMD logo with the slogan.

PMD official logo
PMD official logo

When checking your code with PMD, it makes use of patterns defined by various rules. This tool comes with more than 250 built-in rules. When checking through your source-code, PMD will scan your code against the established rule that you select. If any rule is violated, then PMD will raise an error.

However, PMD is an opensource tool. Users can develop their rules to make PMD adapt to specific project requirements and criteria. Also, with the so many PMD inbuilt rules, one cannot use all of them at a go. Some rules even contradict each other. Others make use of different coding conventions different from the project you are working on.

Supported Platforms and Development Environments

PMD is a cross-platform tool that runs in several operating systems. It includes; Unix, Windows, Linux distributions, macO, and FreeBSD. For reliability and efficiency when writing code, you can integrate the PMD plugin in your favorite integrated development environment (IDE). Some of the supported IDE’s include; Netbeans, JBuilder, Eclipse, IntelliJ IDEA, Maven, TextPad, Ant, CodeGuide, BlueJ, JEdit, JCreator, Emacs and Sun Java Studio. For any updates and supported IDE’s, you can find more information on their official GitHub page Here

Installing PMD plugin to Eclipse IDE

For this article, we will focus on the Eclipse IDE. Below is a step by step process of how to install the PMD plugin in Eclipse.

Step 1) Download and install Eclipse for your operating system. You can find the different setup files on their official download page.

Download Eclipse

Step 2) Navigate to the Help menu on your Eclipse IDE and click on the Install New Software button.

Eclipse Help Menu
Eclipse Help Menu

Step 3) A window will pop up. You don’t have to alter anything here. Click on the Add button. 

Install PMD plugin in Eclipse
Install PMD plugin in Eclipse

Step 4) Another smaller pop-up window will open. You will need to enter the name and the URL location of the package. Enter the details below and click Add;

Name = PMD for Eclipse Update Site

Location = https://dl.bintray.com/pmd/pmd-eclipse-plugin/updates/

Enter name and URL of PMD plugin
Enter name and URL of PMD plugin

Note, since these details (Name and article) were useful at the time of writing this article, you can get more updated information on the Tools/Integrations page. 

Step 5) You should see PMD for Eclipse 4 listed. However, it might take sometime before its listing. It is because some files need to be fetched online, and therefore, your internet speed is critical.

The PMD plugin
The PMD plugin

Step 6) Check the box beside the listed PMD plugin and click Next.

Step 7) On the next screen, accept the terms and conditions and install the PMD plugin.

Accept Terms and Condition for Plugin installation
Accept Terms and Condition for Plugin installation

Step 8) Restart Eclipse.

Working of PMD

PMD analyses code by first parsing through it. This process consists of two main steps;

  • Lexing/Tokenization – This refers to the conversion of a series of characters present in a computer program to a sequence of tokens. 
  • Parsing – It is the process of going through the code and generating an Abstract Syntax Tree (AST).

After the generation of an AST, PMD defined rules are now executed. When analyzing a single file, the rules are implemented one after the other, but when dealing with multiple files, they are run through multithreading. 

Violation of any rule will result in a warning or recommendation being raised in the PMD report. The report will include a particular line in the source code that violated a rule and a recommender message or warning. The report format can either be in XML or HTML.

Features

1. Support for XPath rules

After parsing through the code, PMD generates an Abstract Syntax Tree (AST) similar to an XML document. By querying the file using XPath expressions, PMD can identify nodes that meet specific criteria. This feature provides an API for users to develop their own rules other than those present in PMD.

2. Type Resolution

After PMD has parsed through the code, concrete type information is added to different lines and sections of the code. Let’s take an example of the code below:

import org.s1f4j.Logger;
public class Tuts
{
	private static final logger LOG = Logger.getLogger(Example.class);
	
	public void someMethod(String arg) {
	LOG.debug("This is an error checking message: "+ arg);
	}
}

In the above code, the declaration of LOG is assigned the type logger. It is identified as org.slf4j.Logger. Using the library “slf4j.API”, PMD attaches a concrete instance of the class to the particular AST. Now, when a rule is executed, it can access it.

3. Metrics

The feature became available in PMD in 2017 during the Summer of Code. Metrics is a framework that provides developers a clean and straight forward to access the analyzed code and use code metrics rules. 

Conclusion

I believe this article has given you a good understanding of PMD and how it works. It has proved to be a useful tool for developers, whether working on a small project or development of an extensive system or software. You can visit the official PMD GitHub page for the project updates.

Arun Kumar
Arun did his bachelor in computer engineering and loves enjoying his spare time writing for FOSS Linux. He uses Fedora as the daily driver and loves tinkering with interesting distros on VirtualBox. He works during the day and reads anything tech at night. Apart from blogging, he loves swimming and playing tennis.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

STAY CONNECTED

23,874FansLike
265FollowersFollow
16SubscribersSubscribe

LATEST ARTICLES

How to create an Arch Linux Live USB drive on Ubuntu

create Arch Linux Live USB drive
This article provides a step-by-step guide on creating an Arch Linux USB installation media on Ubuntu PC. The Live USB media can be used to install Arch Linux.
best linux distros beginners
Making the shift to Linux is not as complicated as some people make it out to be. There is a variety of Linux distributions available that cater to the needs of people who are planning on making the jump to Linux from any other operating system.
clipboard manager linux
We have all had that moment when we copied a text, but we first needed another one, and in the process, lost the first one. If you're lucky, you can get it back quickly with a bit of work.