Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Boost Your Java Code Quality with PMD
Priya
Priya

Posted on

     

Boost Your Java Code Quality with PMD

Do you ever find yourself struggling with code smells in your Java projects? You’re not alone! Code smells are simply indicators that your code could use some improvement. In this post, we'll explore howPMD (Programming Mistake Detector) can help you find and fix these pesky code smells effectively.

What Are Code Smells?

Code smells aren’t bugs, but they do suggest that your code could use some improvement to make it clearer, easier to maintain, or more efficient. Here are a few common examples:

  • Long Methods: These are methods that are too long and try to do too many things at once.
  • Duplicated Code: This is when you see the same code in several places.
  • Deep Nesting: This happens when your code has too many nested blocks, making it tough to read.

What is PMD?

PMD (Programming Mistake Detector) is a handy tool that analyzes your source code to spot common programming issues. It helps identify things like unused variables, empty catch blocks, and overly complex methods, making it easier for you to improve your code quality.

Rulesets in PMD

PMD uses predefined rulesets to check your code. These rulesets have different rules that look for various kinds of issues. Here’s a quick look at some common rulesets:

  • Basic: Looks for simple issues like empty catch blocks and unnecessary object creation.
  • Design: Checks if your code follows good design principles and finds overly complex methods and classes.
  • Unused Code: Finds code elements that are defined but never used.

How to Integrate PMD into Your Build Process

Integrating PMD into your build process helps you automatically check for code quality. Here’s how to set it up with Maven:

1. Add PMD Plugin topom.xml

<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-pmd-plugin</artifactId><version>3.21.0</version><configuration><rulesets><ruleset>java-basic</ruleset><ruleset>java-design</ruleset><ruleset>java-unusedcode</ruleset></rulesets></configuration><executions><execution><phase>verify</phase><goals><goal>pmd</goal></goals></execution></executions></plugin></plugins></build>
Enter fullscreen modeExit fullscreen mode

Explanation:

  • <rulesets>: This tells PMD which rulesets to use (like basic, design, and unused code).
  • <phase>verify</phase>: This sets PMD to run during the Mavenverify phase, which happens after tests and before packaging your code.

2. Run PMD

You can run PMD during your Maven build or on its own.

  • During Build: PMD will run automatically during theverify phase when you run:
  mvn clean verify
Enter fullscreen modeExit fullscreen mode
  • Manually: If you want to run PMD separately, just use:
  mvn pmd:pmd
Enter fullscreen modeExit fullscreen mode

This will kick off the PMD analysis.

3. View Reports

After PMD runs, it generates a report showing any issues it found.

  • Locate the Report: You can find the PMD report at:
  target/site/pmd.html
Enter fullscreen modeExit fullscreen mode
  • Report Contents:
    • Summary: A quick overview of how many violations were found.
    • Details: A list of issues, including file names, line numbers, and descriptions.
    • Rulesets: Information about which rulesets were used and their results.

Example Walkthrough

Here’s a simple example to show PMD in action! You can check out the code in myReplit.

Consider the following code:

publicclassUnusedCode{// This field is never usedprivateintunusedField;publicvoidusedMethod(){System.out.println("This method is used.");}}publicclassMain{publicstaticvoidmain(String[]args){UnusedCodeunusedCode=newUnusedCode();}}
Enter fullscreen modeExit fullscreen mode

After runningmvn pmd:pmd, you’ll find the reportpmd.html in thetarget/site/ folder.

If you open it in your browser, it will look something like this:

PMD Report

Understanding the PMD Report

  1. Overview: Displays the PMD version (6.55.0) and last published date.
  2. Violations by Priority:
    • Main.java:
      • Rule:UseUtilityClass
      • Violation: "All methods are static. Consider using a utility class."
      • Line: 1–5
    • UnusedCode.java:
  3. Files Section: Details about violations for each analyzed file, highlighting areas for improvement.

Stopping Build Process if There Are Violations

When PMD finds errors during a Maven build, the build doesn’t stop by default. It will report the violations and keep going.

You can change this behavior so the build fails if certain limits of violations are hit. Here’s how:

<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-pmd-plugin</artifactId><version>3.21.0</version><configuration><rulesets><ruleset>java-basic</ruleset><ruleset>java-design</ruleset><ruleset>java-unusedcode</ruleset></rulesets></configuration><executions><execution><phase>verify</phase><goals><goal>pmd</goal><!-- Checks for violations and fails the build if found --><goal>check</goal></goals></execution></executions></plugin></plugins></build>
Enter fullscreen modeExit fullscreen mode

Explanation:

  • <goal>check</goal>: This tells PMD to check for violations in the report. If any are found, it will fail the build.

Now, if you runmvn clean verify, your build will stop if there are violations.

Before adding thecheck goal,

Build Success Image

After adding it,

Build Failed Image

Conclusion

By integrating PMD into your Java projects, you can automatically spot and fix code smells, making your code more maintainable and efficient.

Feel free to share your experiences with PMD or ask any questions in the comments below.

Happy coding! 😊

Top comments(4)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
aloisseckar profile image
Alois Sečkár
I am from Czechia, born in 1988. Studied computer science at KIT VŠE, Prague. Currently working as senior Java & JS developer for Eviden.
  • Email
  • Location
    Prague, Czechia
  • Education
    KIT VŠE, Prague
  • Pronouns
    He
  • Work
    Senior application developer @ Eviden
  • Joined

I guess PMD is a lightweight alternative for personal use, but if I want to build a solution for real-world project, I would probably favor SonarQube.

CollapseExpand
 
priya01 profile image
Priya
Software Engineer | Backend development with expertise in Django, MySQL, Ember.js, Java, Python, and REST APIs | Open to freelance projects and collaborations
  • Email
  • Location
    India
  • Education
    Computer Science & Engineering
  • Work
    Software Engineer
  • Joined

Thank you for your comment,@aloisseckar !

I don’t know much about SonarQube, but I’ll definitely check it out. Currently, I am using PMD to create custom rules in Java. Does SonarQube offer similar functionality?

CollapseExpand
 
aloisseckar profile image
Alois Sečkár
I am from Czechia, born in 1988. Studied computer science at KIT VŠE, Prague. Currently working as senior Java & JS developer for Eviden.
  • Email
  • Location
    Prague, Czechia
  • Education
    KIT VŠE, Prague
  • Pronouns
    He
  • Work
    Senior application developer @ Eviden
  • Joined
Thread Thread
 
priya01 profile image
Priya
Software Engineer | Backend development with expertise in Django, MySQL, Ember.js, Java, Python, and REST APIs | Open to freelance projects and collaborations
  • Email
  • Location
    India
  • Education
    Computer Science & Engineering
  • Work
    Software Engineer
  • Joined

Thanks for the link 😊! I’ll check out the docs.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer | Backend development with expertise in Django, MySQL, Ember.js, Java, Python, and REST APIs | Open to freelance projects and collaborations
  • Location
    India
  • Education
    Computer Science & Engineering
  • Work
    Software Engineer
  • Joined

More fromPriya

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp