RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


PMD Squashes Code Bugs : Page 3

Despite being among the most effective ways of finding defects and improving code quality, code reviews are rarely done with any consistency. Enter PMD, a static analysis tool that can make reviewing code easier and more fun.


PMD in Action

Click to enlarge
Figure 5. Displaying PMD Rule Violations

PMD is quite flexible. You can use it in two basic ways:

  1. Wait for PMD to automatically analyze a file each time it is saved or added to the project
  2. Manually execute it against selected files, folders, or projects

PMD displays rule violations in the "Tasks" view, among TODOs and other task entries, or in the special PMD view, which gives a more tailored display and more specific filtering options (see Sidebar 1. PMD Rules to see a listing of all main PMD rule sets). The "Violations Outline" panel gives another, more summarized view of PMD rule violations (see Figure 5).

PMD violations have the following five levels of severity (see Figure 6):

Click to enlarge
Figure 6. PMD Rule Violations Are Nicely Detailed in the "PMD" View

  1. Error (high)
  2. Error
  3. Warning (high)
  4. Warning
  5. Information

This is mainly to help prioritize fixes, and the level of each rule can be easily configured. Violations are (by default) ordered by level of severity, and it is easy to filter out certain priority levels. You can also chose to display only the violations of the current project or of the selected file.

Rules aren't meant to be applied blindly. If you're not sure why a particular violation is being detected, or think it doesn't apply in your case, you can refresh your memory of the rule by displaying the details ("Show details" in the contextual menu) (see Figure 7). And, as you will see shortly, if a rule is not justified in certain circumstances, there are ways to deactivate it.

Detecting Cut-and-Pasted Code
Click to enlarge
Figure 7. Displaying the Details of a Particular Rule

Cutting and pasting code between classes is a bad habit. Areas of cut-and-pasted code increase maintenance costs unnecessarily, and indicate in the very least a good candidate for refactoring. In many cases, they are high-risk zones for potential errors.

PMD comes with a useful tool for detecting cut-and-pasted code called CPD (Cut and Paste Detector). You can run it from the contextual menu on the project, using the "PMD -> Find Suspect Cut and Paste" menu option.

Unfortunately, at the time of writing, the results of this tool were not integrated into the IDE. The tool generates a text file called cpd-report.txt in the /report directory, which contains copy-and-paste suspects, as shown here:

Found a 18 line (56 tokens) duplication in the following files: 
Starting at line 69 of 
/home/taronga/Documents/articles/HotelWorld/src/main/java/com/wakaleo/tutorials/hotelworld/model/HotelModel.java Starting at line 82 of
/home/taronga/Documents/articles/HotelWorld/src/main/java/com/wakaleo/tutorials/hotelworld/model/HotelModel.java List hotelsFound = findHotelsByLanguage(language); Hotel hotel = null; for(int i = 0; i < hotels.length; i++) { hotel = (Hotel) hotels[i]; if (hotel.getCity().equalsIgnoreCase(city)) { hotelsFound.add(hotel); } } return hotelsFound; } /** * Find hotels where a given language is spoken. * @param language * @return */ public List findHotelsByLanguage(Language language) {

You can customize the minimum size of a copy-and-paste zone suspect in the workbench preferences under PMD->CPD Preferences. Just adjust the "Minimum tile size" field, and specify the minimum number of lines.

Report Generation from Within Eclipse
Many people are very attached to hard-copy outputs. If you are among them, you may appreciate the ability to generate PMD rule violation reports in CSV, HTML, TXT, and XML formats. Just go to the contextual menu on the project, and select "PMD -> Generate Reports". The reports will be generated in the /report directory of the current project. Figure 8 shows an example of an HTML report.

Click to enlarge
Figure 8. Generating a PMD Report from Eclipse

All rules have exceptions. You will have occasions when PMD gets it wrong, and you have a legitimate reason for not respecting one of the PMD rules. For example, consider the following code:

    /** Countries : USA */
    public static final Country USA = new Country("us","United States");

Suppose that your company standards impose a minimum of four letters for variable names. In this case, PMD will incorrectly generate an error. To get around this, you can mark a violation as "Reviewed", which basically tells PMD that you've seen the issue and that it's fine by you. Click on the error and open the contextual menu, then select "Mark as reviewed". PMD will insert a special comment similar to the following:

    /** Countries : USA */
    // @PMD:REVIEWED:ShortVariable: by taronga on 4/13/06 7:25 AM
    public static final Country USA = new Country("us","United States");

As long as you don't remove it, PMD will now ignore this violation for this particular case.

Another way of doing this while writing the code is to use the "NOPMD" marker, as follows:

    // These are x and y coordinates, so short variable names are OK
    int x = 0; // NOPMD
    int y = 0; // NOPMD

The marker deactivates the ShortVariable rule for the variables.

A third technique, particularly useful for generated classes or legacy code, is to use the PMD SuppressWarnings annotation. In the following class, all PMD warnings are suppressed:

    public class Country {

You may just want to suppress certain rules for a given class. In the following generated class, for example, private variables are prefixed with an underscore, which is not in line with PMD's rules concerning JavaBeans. To get around this, you just suppress a specific PMD rule:

    public class Country {
        private String _code;
        public String getCode(){ 
            return _code; 

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date