Suppressing PMD Warnings in Java and Kotlin

Recently I was working on a project which had both Java and Kotlin classes, and used the PMD Source Code Analyzer.

Occasionally, it was necessary to suppress a PMD warning, for example when you have a long line because of a code template.

Suppressing warnings is slightly different for each language, and can be easy to confuse when constantly switching between the two.

Java

In Java, decorate your class or method with the @SuppressWarnings annotation, and prefix the name of the rule with PMD. for example:

@SuppressWarnings("PMD.AvoidLiteralsInIfCondition") 
public abstract class ServiceBase...

You can also supply an array:

@SuppressWarnings({"PMD.AvoidLiteralsInIfCondition", "PMD.LongMethod"})
public class Query...    

Kotlin

In Kotlin the annotation is named @Supress. Do not use the PMD. prefix:

@Suppress("LongMethod", "MaxLineLength")
object SelectableGenerator...

Constants

Another useful tip, to avoid breaking rules like MagicNumber, is to use constants.

In Java, this is simple enough:

final int MAX_TRIES = 3;

In Kotlin, use a companion object:

companion object {
    const val MAX_TRIES = 3;
}    

I hope you may find this useful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s