Code Inspection - leortyz/softwareEngineeringResources GitHub Wiki
- Use PMD as a code quality metric tool for preemptive defect detection.
- Obtain an html report with the different detected issues in the code using Maven.
- Eclipse IDE for Java Developers >= 2021β03 Download from Eclipse || Get executable
- Git
PMD is a source code analyzer. It finds common programming flaws like unused variables, empty catch blocks, unnecessary object creation, and so forth [1]. Like other tools, PMD can verify that coding conventions and standards are followed. PMD is more focused on preventive defect detection. It comes with a vast set of rules and is highly configurable. PMD can also configure - in a simple way - particular rules to use in a specific project [2].
PMD integrates well with IDEs such as Eclipse and NetBeans, and it also fits well into the build process thanks to its smooth integration with Ant and Maven [2].
For this lab, we will use Eclipse and Maven together with PMD to inspect the source code of a project.
β
Most Eclipse download include the maven tooling already. If it is missing in your installation, follow these steps, otherwise jump to part two:
- Open the plugin installation window by selecting the βhelp >> Install new softwareβ.
- Click on add and type Maven for the name and http://download.eclipse.org/releases/neon for the location.
- Click βAddβ again and wait until the process finishes.
- Check βMaven Integration for Eclipseβ under βGeneral Purpose Toolsβ.
- Download pmd-bin-6.35.0.zip
- Extract the zip-archive, e.g. to C:\pmd-bin-6.35.0
- Add folder C:\pmd-bin-6.35.0\bin to PATH, either
- Permanently: Using System Properties dialog > Environment variables > Append to PATH variable
- Temporarily, at command line: SET PATH=C:\pmd-bin-6.35.0\bin;%PATH%
- Execute at command line: pmd.bat -d c:\src -R rulesets/java/quickstart.xml -f text
or download it from the eclipse marketplace
- Fork the following repository: CodeInspection and open the project in eclipse.
- PMD will not be activated for the project by default. Open the project properties window by clicking in βProject >> Propertiesβ.
- Select βPMDβ on the side bar and check βEnabled PMD β.
- Look at all the rulesets that come with PMD, leave the default set of rules.
- Click βApply and Closeβ and βYesβ.
β
Go to βWindow >> Preferencesβ, select βPMDβ and check βCheck code after savingβ
To run PMD, right click on the project and select βPMD >> Check codeβ
Two new windows are displayed with all violations. Each violation has its priority represented by a color and corresponding rule. The meaning of the colors is:
- Red is blocker >>> High priority.
- Cyan is critical >>> Medium priority.
- Green is urgent >>> Medium priority.
- Pink is Important >>> Medium priority.
- Blue is Warning >>> Low priority.
If you see that files are duplicated in the Violation Overview Window, check code again.
PMD shows the violations next to the lines that generate them.
We can filter violations using the color indicators on the top right of Violations Overview window.
For example, if we filter only by critical violations, Violations Overview window shows that Email.java and EmalApp.java have 2 and 3 violations respectively for the rule βSystemPrintlnβ. If we double-click on an element, the Violation Outline window will update showing all errors related to a file and some important data such as the violation line, the affected rule, and the error message.
We can right-click on a violation and select "Show details..." for more information and an example solution.
For more information about configurations, refer to section 2 and 3 from chapter 22 of the book [2] and PMD website [1].
A PMD ruleset is simply an XML file that lists a set of rules that fit the project. You can include entire rulesets, or selectively choose specific rules from within other rulesets. You can also provide extra parameters to certain rules to customize their behavior. To do so, follow these steps:
- Right click on the project, then βNew >> Other >> XML >> XML Fileβ.
- Select the project, enter a file name as β_ ruleset β
- Click βSourceβ in the bottom tab to change the view and edit the file directly.
- Here is a fragment of a typical configuration document, copy and paste into the file:
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="<your name> Rules"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>
Code Inspection Lab, <your full name>
</description>
</ruleset>
- Letβs reference a complete ruleset. Add the following line below the description tag:
<rule ref="category/java/performance.xml" />
This ruleset comes by default with PMD and it has rules that flag suboptimal code.
- Now, add another reference, but exclude some rules from the ruleset:
<rule ref="category/java/bestpractices.xml">
<exclude name="SystemPrintln" />
</rule>
This ruleset also comes by default with PMD and it has rules which enforce generally accepted best practices but excluding βSystemPrintlnβ rule.
- We can add rules from a specific ruleset as follow:
<rule ref="category/java/design.xml/ImmutableField" />
<rule ref="category/java/design.xml/UseUtilityClass">
<priority>1</priority>
</rule>
Here, we are adding βImmutableFieldβ rule and βUseUtilityClassβ rule from the Design ruleset and changing its priority to 1. Priority is an integer ranging from 1 to 5, with 1 being the highest priority.
For more information about PMD rulesets, refer to PMD documentation [3]
- To use an external ruleset, we need to go to the PMD Configuration Window. Go to βWindow >> Preferences ο PMD ο Rule Configurationsβ.
- Check βUse global rule managementβ, then group rules by βRule Setβ.
- Select all the rule sets and click in the βXβ button to delete them.
- Click "Import rule set..." (under the "x"), browse your file and Click βOkβ.
- The rules we added are not listed yet, press "Apply and close", then "Yes".
- Return to PMD Configuration Window. Notice that the checkbox next to the rule names is unchecked.
- Press "Apply and close", then "Yes".
- Right click on the project and select βPMD >> Clear Violationsβ. Then βPMD ο Check Code.β
Note that it is possible to configure the properties for each rule we add. To learn more about rulesets and their properties, refer to PMD Java Rules [3]
- Open PMD configuration window, select Reports and check βhtml.β
- Right-click the project then click βPMD ο Generate Report.β
- A folder named reports is created in the tree project. Open it and double click the βpmd-report.htmlβ to see the full report.
Sometimes you will have a legitimate reason for not respecting one of the PMD rules. PMD provides several methods by which Rule violations can be suppressed. We will be using comments and annotations.
- Go to Email.java. See that line 5 has a violation related to ImmutableField rule.
- Write βNOPMDβ as a comment in the same line where the violation occurred.
- Optionally, add a message placed after the NOPMD marker. This will get placed in the report.
4. Go to EmailApp.java and check the violation. The rule violated is βUseUtilityClassβ. 5. Write an annotation above the line as follow:
Please note that only that rule will be ignored.
6. Save the file and see the results.
For more information about suppressing rules, check the PMD website [4] and section 7 from chapter 22 of the book [2]
PMD comes with a useful tool for detecting cut-and-pasted code called CPD (Cut-and-Paste Detector). Follow these steps to use it and generate a report.
- Just for demonstration purpose, copy and paste the βrandomPasswordβ method from Email.java to EmalApp.java.
- Right-click the project and select βPMD >> Find Suspect Cut and Pasteβ from menu options.
- Select βjavaβ for Language, then click βOkβ.
- CPD View Window will open with the results. Also, a text file called cpd-report.txt will be generated in the /report directory.
- Revert the changes made in EmailApp.java.
- Open βpom.xmlβ file
- Add the following lines under project tag to install all the necessary plugins:
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.13.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<rulesets>
<ruleset><yourname>_ruleset.xml</ruleset>
</rulesets>
</configuration>
</plugin>
</plugins>
</reporting>
The ruleset tag is used to specify a file that contains rules to use in the checking process. In this case, we are telling the plugin to use our ruleset file. 3. Save the file, right Click on it, then βRun as >> Maven buildβ¦β 4. Type βsite" for the Goals and Click Run.
- Wait for the process to finish.
- Go to your project directory, open βtarget>> siteβ. This folder is visible from the tree project in Eclipse too.
- Several html files are shown. Open βindex.html".
- Click on βProject Reports ο PMDβ to see a detailed PMD report of your project.
β
- Delete all comments and annotations from the code.
- Add the following ruleset and rules:
- Code Style Ruleset
- Rule βBeanMembersShouldSerializeβ from Error Prone ruleset with a priority of 2
- Rule βUseLocaleWithCaseConvertionβ from Error Prone ruleset
- Rule βCommentRequiredβ from Documentation ruleset with these properties set to βIgnoredβ:
- classCommentRequirement
- headerCommentRequirement
- fieldCommentRequirement
TIP: Refer to the PMD Java Rules [3].
The errors per class are show below:
- Generate an html report, make a copy and save it somewhere on your disk.
- Correct any violation in the code that have been generated in the report.
- Generate a new report (without violations).
- Lab report with screenshots of the process.
- Two PMD reports.
- Include in the report the url of the repository where you performed the lab.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ¦ββββββββ
β Description β Value β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββ£
β Project code (in a repository) β 50 β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββ£
β Lab report β 50 β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββ£
β Penalty per hour or fraction of delay β -30 β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββ£
β Penalty for not uploading required deliverables as specified β -30 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ©ββββββββ