Since: PMD 0.3
If you have a class that has nothing but static methods, consider making it a Singleton. Note that this doesn't apply to abstract classes, since their subclasses may well include non-static methods. Also, if you want this class to be a Singleton, remember to add a private constructor to prevent instantiation.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.UseSingleton
Example:
public class MaybeASingleton { public static void foo() {} public static void bar() {} }
Since: PMD 0.9
Avoid unnecessary if..then..else statements when returning a boolean.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.SimplifyBooleanReturns
Example:
public class Foo { private int bar =2; public boolean isBarEqualsTo(int x) { // this bit of code if (bar == x) { return true; } else { return false; } // can be replaced with a simple // return bar == x; } }
Since: PMD 1.05
Avoid unnecessary comparisons in boolean expressions - this complicates simple code.
This rule is defined by the following XPath expression:
//EqualityExpression/PrimaryExpression /PrimaryPrefix/Literal/BooleanLiteral
Example:
public class Bar { // can be simplified to // bar = isFoo(); private boolean bar = (isFoo() == true); public isFoo() { return false;} }
Since: PMD 1.0
Switch statements should have a default label.
This rule is defined by the following XPath expression:
//SwitchStatement[not(SwitchLabel[@Default='true'])]
Example:
public class Foo { public void bar() { int x = 2; switch (x) { case 2: int j = 8; } } }
Since: PMD 1.0
Deeply nested if..then statements are hard to read.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.AvoidDeeplyNestedIfStmtsRule
Example:
public class Foo { public void bar(int x, int y, int z) { if (x>y) { if (y>z) { if (z==x) { // whew, too deep } } } } }
This rule has the following properties:
Name | Default value | Description |
---|---|---|
problemDepth | 3 | The if statement depth reporting threshold |
Since: PMD 1.0
Reassigning values to parameters is a questionable practice. Use a temporary local variable instead.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.AvoidReassigningParameters
Example:
public class Foo { private void foo(String bar) { bar = "something else"; } }
Since: PMD 1.02
A high ratio of statements to labels in a switch statement implies that the switch statement is doing too much work. Consider moving the statements into new methods, or creating subclasses based on the switch variable.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.SwitchDensityRule
Example:
public class Foo { public void bar(int x) { switch (x) { case 1: { // lots of statements break; } case 2: { // lots of statements break; } } } }
This rule has the following properties:
Name | Default value | Description |
---|---|---|
minimum | 10 | The switch statement ratio reporting threshold |
Since: PMD 1.04
Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to discern. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call super(). If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Note that this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls a private method bar() that calls a public method buz(), this denotes a problem.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.ConstructorCallsOverridableMethod
Example:
public class SeniorClass { public SeniorClass(){ toString(); //may throw NullPointerException if overridden } public String toString(){ return "IAmSeniorClass"; } } public class JuniorClass extends SeniorClass { private String name; public JuniorClass(){ super(); //Automatic call leads to NullPointerException name = "JuniorClass"; } public String toString(){ return name.toUpperCase(); } }
Since: PMD 1.04
Instantiation by way of private constructors from outside of the constructor's class often causes the generation of an accessor. A factory method, or non-privitization of the constructor can eliminate this situation. The generated class file is actually an interface. It gives the accessing class the ability to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter. This turns a private constructor effectively into one with package scope, and is challenging to discern.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.AccessorClassGeneration
Example:
public class Outer { void method(){ Inner ic = new Inner();//Causes generation of accessor class } public class Inner { private Inner(){} } }
Since: PMD 1.1
If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime.
This rule is defined by the following XPath expression:
//FieldDeclaration [@Final='true' and @Static='false'] [not (../../../../ClassOrInterfaceDeclaration[@Interface='true'])] /VariableDeclarator/VariableInitializer/Expression /PrimaryExpression/PrimaryPrefix/Literal
Example:
public class Foo { public final int BAR = 42; // this could be static and save some space }
Since: PMD 1.2.2
Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.CloseResource
Example:
public class Bar { public void foo() { Connection c = pool.getConnection(); try { // do stuff } catch (SQLException ex) { // handle exception } finally { // oops, should close the connection using 'close'! // c.close(); } } }
This rule has the following properties:
Name | Default value | Description |
---|---|---|
types | Connection,Statement,ResultSet |
Since: PMD 1.5
A nonstatic initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing.
This rule is defined by the following XPath expression:
//Initializer[@Static='false']
Example:
public class MyClass { // this block gets run before any call to a constructor { System.out.println("I am about to construct myself"); } }
Since: PMD 1.5
By convention, the default label should be the last label in a switch statement.
This rule is defined by the following XPath expression:
//SwitchStatement [not(SwitchLabel[position() = last()][@Default='true'])] [SwitchLabel[@Default='true']]
Example:
public class Foo { void bar(int a) { switch (a) { case 1: // do something break; default: // the default case should be last, by convention break; case 2: break; } } }
Since: PMD 1.5
A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels.
This rule is defined by the following XPath expression:
//SwitchStatement//BlockStatement/Statement/LabeledStatement
Example:
public class Foo { void bar(int a) { switch (a) { case 1: // do something break; mylabel: // this is legal, but confusing! break; default: break; } } }
Since: PMD 1.8
A call to Collection.toArray can use the Collection's size vs an empty Array of the desired type.
This rule is defined by the following XPath expression:
//PrimaryExpression [PrimaryPrefix/Name[ends-with(@Image, 'toArray')]] [ PrimarySuffix/Arguments/ArgumentList/Expression /PrimaryExpression/PrimaryPrefix/AllocationExpression /ArrayDimsAndInits/Expression/PrimaryExpression/PrimaryPrefix/Literal[@Image='0'] ]
Example:
class Foo { void bar(Collection x) { // A bit inefficient x.toArray(new Foo[0]); // Much better; this one sizes the destination array, avoiding // a reflection call in some Collection implementations x.toArray(new Foo[x.size()]); } }
Since: PMD 1.8
Avoid equality comparisons with Double.NaN - these are likely to be logic errors.
This rule is defined by the following XPath expression:
//EqualityExpression[@Image='=='] /PrimaryExpression/PrimaryPrefix /Name[@Image='Double.NaN' or @Image='Float.NaN']
Example:
public class Bar { boolean x = (y == Double.NaN); }
Since: PMD 1.9
Inexperienced programmers sometimes confuse comparison concepts and use equals() to compare to null.
This rule is defined by the following XPath expression:
//PrimaryExpression [ PrimaryPrefix/Name[ends-with(@Image, 'equals')] or PrimarySuffix[ends-with(@Image, 'equals')] ] [PrimarySuffix/Arguments/ArgumentList[count(Expression)=1] /Expression/PrimaryExpression/PrimaryPrefix /Literal/NullLiteral]
Example:
class Bar { void foo() { String x = "foo"; if (x.equals(null)) { // bad! doSomething(); } } }
Since: PMD 1.9
In an "if" expression with an "else" clause, avoid negation in the test. For example, rephrase: if (x != y) diff(); else same(); as: if (x == y) same(); else diff(); Most "if (x != y)" cases without an "else" are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?".
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.ConfusingTernary
Example:
public class Foo { boolean bar(int x, int y) { return (x != y) ? diff : same; } }
Since: PMD 2.0
Avoid instantiating an object just to call getClass() on it; use the .class public member instead.
This rule is defined by the following XPath expression:
//PrimarySuffix [@Image='getClass'] [parent::PrimaryExpression [PrimaryPrefix/AllocationExpression] [count(PrimarySuffix) = 2] ]
Example:
public class Foo { // Replace this Class c = new String().getClass(); // with this: Class c = String.class; }
Since: PMD 2.0
Avoid idempotent operations - they are have no effect.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.IdempotentOperations
Example:
public class Foo { public void bar() { int x = 2; x = x; } }
Since: PMD 2.0
Be sure to specify a Locale when creating a new instance of SimpleDateFormat.
This rule is defined by the following XPath expression:
//AllocationExpression [ClassOrInterfaceType[@Image='SimpleDateFormat']] [Arguments[@ArgumentCount=1]]
Example:
public class Foo { // Should specify Locale.US (or whatever) private SimpleDateFormat sdf = new SimpleDateFormat("pattern"); }
Since: PMD 2.0
Identifies private fields whose values never change once they are initialized either in the declaration of the field or by a constructor. This aids in converting existing classes to immutable classes.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.ImmutableField
Example:
public class Foo { private int x; // could be final public Foo() { x = 7; } public void foo() { int a = x + 2; } }
Since: PMD 2.0
When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Turkish.
This rule is defined by the following XPath expression:
//PrimaryExpression [PrimaryPrefix/Name [ends-with(@Image, 'toLowerCase') or ends-with(@Image, 'toUpperCase')] ] [PrimarySuffix[position() = 1]/Arguments[@ArgumentCount=0]]
Example:
class Foo { // BAD if (x.toLowerCase().equals("list"))... /* This will not match "LIST" when in Turkish locale The above could be if (x.toLowerCase(Locale.US).equals("list")) ... or simply if (x.equalsIgnoreCase("list")) ... */ // GOOD String z = a.toLowerCase(Locale.EN); }
Since: PMD 2.1
Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead.
This rule is defined by the following XPath expression:
//ClassOrInterfaceDeclaration[@Final='true'] /ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration /FieldDeclaration[@Protected='true']
Example:
public final class Bar { private int x; protected int y; // <-- Bar cannot be subclassed, so is y really private or package visible??? Bar() {} }
Since: PMD 2.2
Identifies a possible unsafe usage of a static field.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.AssignmentToNonFinalStatic
Example:
public class StaticField { static int x; public FinalFields(int y) { x = y; // unsafe } }
Since: PMD 3.0
A class that has private constructors and does not have any static methods or fields cannot be used.
This rule is defined by the following XPath expression:
//ClassOrInterfaceDeclaration[@Nested='false'][ ( count(./ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/ConstructorDeclaration)>0 and count(./ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/ConstructorDeclaration) = count(./ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/ConstructorDeclaration[@Private='true']) ) and count(.//MethodDeclaration[@Static='true'])=0 and count(.//FieldDeclaration[@Private='false'][@Static='true'])=0 ]
Example:
/* This class is unusable, since it cannot be instantiated (private constructor), and no static method can be called. */ public class Foo { private Foo() {} void foo() {} }
Since: PMD 3.0
Method level synchronization can backfire when new code is added to the method. Block-level synchronization helps to ensure that only the code that needs synchronization gets it.
This rule is defined by the following XPath expression:
//MethodDeclaration[@Synchronized='true']
Example:
public class Foo { // Try to avoid this synchronized void foo() { } // Prefer this: void bar() { synchronized(this) { } } }
Since: PMD 3.0
A switch statement without an enclosed break statement may be a bug.
This rule is defined by the following XPath expression:
//SwitchStatement [count(.//BreakStatement)=0] [count(SwitchLabel) > 0] [count(BlockStatement/Statement/ReturnStatement) + count(BlockStatement/Statement/ThrowStatement) < count (SwitchLabel)]
Example:
public class Foo { public void bar(int status) { switch(status) { case CANCELLED: doCancelled(); // break; hm, should this be commented out? case NEW: doNew(); case REMOVED: doRemoved(); } } }
Since: PMD 3.0
Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary; thus it's usually safer to call notifyAll() instead.
This rule is defined by the following XPath expression:
//StatementExpression/PrimaryExpression [count(PrimarySuffix/Arguments/ArgumentList) = 0] [ PrimaryPrefix[./Name[@Image='notify' or ends-with(@Image,'.notify')] or @Image='notify' or (./AllocationExpression and ../PrimarySuffix[@Image='notify']) ] ]
Example:
public class Foo { void bar() { x.notify(); // If many threads are monitoring x, only one (and you won't know which) will be notified. // use instead: x.notifyAll(); } }
Since: PMD 3.0
Each caught exception type should be handled in its own catch clause.
This rule is defined by the following XPath expression:
//CatchStatement/FormalParameter /following-sibling::Block//InstanceOfExpression/PrimaryExpression/PrimaryPrefix /Name[ @Image = ./ancestor::Block/preceding-sibling::FormalParameter /VariableDeclaratorId/@Image ]
Example:
try { // Avoid this // do something } catch (Exception ee) { if (ee instanceof IOException) { cleanup(); } } try { // Prefer this: // do something } catch (IOException ee) { cleanup(); }
Since: PMD 3.0
The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods. If the class is intended to be used as a base class only (not to be instantiated direcly) a protected constructor can be provided prevent direct instantiation.
This rule is defined by the following XPath expression:
//ClassOrInterfaceDeclaration [@Abstract='true' and count( .//MethodDeclaration[@Abstract='true'] )=0 ] [count(ImplementsList)=0] [count(.//ExtendsList)=0]
Example:
public abstract class Foo { void int method1() { ... } void int method2() { ... } // consider using abstract methods or removing // the abstract modifier and adding protected constructors }
Since: PMD 3.1
No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
This rule is defined by the following XPath expression:
//Expression [ConditionalOrExpression [EqualityExpression[@Image='=='] //NullLiteral and UnaryExpressionNotPlusMinus [@Image='!']//InstanceOfExpression[PrimaryExpression //Name/@Image = ancestor::ConditionalOrExpression/EqualityExpression /PrimaryExpression/PrimaryPrefix/Name/@Image]] or ConditionalAndExpression [EqualityExpression[@Image='!=']//NullLiteral and InstanceOfExpression [PrimaryExpression[count(PrimarySuffix[@ArrayDereference='true'])=0] //Name/@Image = ancestor::ConditionalAndExpression /EqualityExpression/PrimaryExpression/PrimaryPrefix/Name/@Image]]]
Example:
class Foo { void bar(Object x) { if (x != null && x instanceof Bar) { // just drop the "x != null" check } } }
Since: PMD 3.2
Use equals() to compare object references; avoid comparing them with ==.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.CompareObjectsWithEquals
Example:
class Foo { boolean bar(String a, String b) { return a == b; } }
Since: PMD 3.3
Position literals first in String comparisons - that way if the String is null you won't get a NullPointerException, it'll just return false.
This rule is defined by the following XPath expression:
//PrimaryExpression[ PrimaryPrefix[Name [ (ends-with(@Image, '.equals')) ] ] [ (../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal) and ( count(../PrimarySuffix/Arguments/ArgumentList/Expression) = 1 ) ] ] [not(ancestor::Expression/ConditionalAndExpression//EqualityExpression[@Image='!=']//NullLiteral)] [not(ancestor::Expression/ConditionalOrExpression//EqualityExpression[@Image='==']//NullLiteral)]
Example:
class Foo { boolean bar(String x) { return x.equals("2"); // should be "2".equals(x) } }
Since: PMD 3.3
Avoid unnecessarily creating local variables
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.UnnecessaryLocalBeforeReturn
Example:
public class Foo { public int foo() { int x = doSomething(); return x; // instead, just 'return doSomething();' } }
Since: PMD 3.4
Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possible by instantiating the object directly. Static singletons are usually not needed as only a single instance exists anyway. Other possible fixes are to synchronize the entire method or to use an initialize-on-demand holder class (do not use the double-check idiom). See Effective Java, item 48.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.NonThreadSafeSingleton
Example:
private static Foo foo = null; //multiple simultaneous callers may see partially initialized objects public static Foo getFoo() { if (foo==null) foo = new Foo(); return foo; }
This rule has the following properties:
Name | Default value | Description |
---|---|---|
checkNonStaticMethods | Do not set this to false and checkNonStaticFields to true | |
checkNonStaticFields | Do not set this to true and checkNonStaticMethods to false |
Since: PMD 3.4
Uncommented Empty Method finds instances where a method does not contain statements, but there is no comment. By explicitly commenting empty methods it is easier to distinguish between intentional (commented) and unintentional empty methods.
This rule is defined by the following XPath expression:
//MethodDeclaration/Block[count(BlockStatement) = 0 and @containsComment = 'false']
Example:
public void doSomething() { }
Since: PMD 3.4
Uncommented Empty Constructor finds instances where a constructor does not contain statements, but there is no comment. By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors.
This rule is defined by the following XPath expression:
//ConstructorDeclaration[@Private='false'][count(BlockStatement) = 0 and ($ignoreExplicitConstructorInvocation = 'true' or not(ExplicitConstructorInvocation)) and @containsComment = 'false']
Example:
public Foo() { super(); }
This rule has the following properties:
Name | Default value | Description |
---|---|---|
ignoreExplicitConstructorInvocation | Ignore explicit constructor invocation when deciding whether constructor is empty or not |
Since: PMD 3.5
An interface should be used only to model a behaviour of a class: using an interface as a container of constants is a poor usage pattern.
This rule is defined by the following XPath expression:
//ClassOrInterfaceDeclaration[@Interface="true"] [ count(.//MethodDeclaration)=0 and count(.//FieldDeclaration)>0 ]
Example:
public interface ConstantsInterface { public static final int CONSTANT1=0; public static final String CONSTANT2="1"; }
Since: PMD 3.6
SimpleDateFormat is not synchronized. Sun recomends separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized either on method or block level.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.UnsynchronizedStaticDateFormatter
Example:
public class Foo { private static final SimpleDateFormat sdf = new SimpleDateFormat(); void bar() { sdf.format(); // bad } synchronized void foo() { sdf.format(); // good } }
Since: PMD 3.7
Throwing a new exception from a catch block without passing the original exception into the new exception will cause the true stack trace to be lost, and can make it difficult to debug effectively.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.PreserveStackTrace
Example:
public class Foo { void good() { try{ Integer.parseInt("a"); } catch(Exception e){ throw new Exception(e); } } void bad() { try{ Integer.parseInt("a"); } catch(Exception e){ throw new Exception(e.getMessage()); } } }
Since: PMD 3.9
The isEmpty() method on java.util.Collection is provided to see if a collection has any elements. Comparing the value of size() to 0 merely duplicates existing behavior.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.UseCollectionIsEmpty
Example:
public class Foo { void good() { List foo = getList(); if (foo.isEmpty()) { // blah } } void bad() { List foo = getList(); if (foo.size() == 0) { // blah } } }
Since: PMD 4.1
A class with only private constructors should be final, unless the private constructor is called by a inner class.
This rule is defined by the following XPath expression:
TypeDeclaration[count(../TypeDeclaration) = 1]/ClassOrInterfaceDeclaration [@Final = 'false'] [count(./ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/ConstructorDeclaration[@Private = 'true']) >= 1 ] [count(./ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/ConstructorDeclaration[(@Public = 'true') or (@Protected = 'true') or (@PackagePrivate = 'true')]) = 0] [not(.//ClassOrInterfaceDeclaration)]
Example:
public class Foo { //Should be final private Foo() { } }
Since: PMD 4.1
An empty method in an abstract class should be abstract instead, as developer may rely on this empty implementation rather than code the appropriate one.
This rule is defined by the following XPath expression:
//ClassOrInterfaceDeclaration[@Abstract = 'true'] /ClassOrInterfaceBody /ClassOrInterfaceBodyDeclaration /MethodDeclaration[@Abstract = 'false' and @Native = 'false'] [ ( boolean(./Block[count(./BlockStatement) = 1]/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Literal/NullLiteral) = 'true' ) or ( boolean(./Block[count(./BlockStatement) = 1]/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Literal[@Image = '0']) = 'true' ) or ( boolean(./Block[count(./BlockStatement) = 1]/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Literal[string-length(@Image) = 2]) = 'true' ) or ( ( (boolean(./Block/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Literal[@Image = '']) = 'true' ) ) and ( count (./Block/*) = 1 ) ) or ( count (./Block/*) = 0 ) ]
Example:
public abstract class ShouldBeAbstract { public Object couldBeAbstract() { // Should be abstract method ? return null; } public void couldBeAbstract() { } }
Since: PMD 3.1
This field is used in only one method and the first usage is assigning a value to the field. This probably means that the field can be changed to a local variable.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.SingularField
Example:
public class Foo { private int x; //Why bother saving this? public void foo(int y) { x = y + 5; return x; } }
This rule has the following properties:
Name | Default value | Description |
---|---|---|
CheckInnerClasses | Check inner classes | |
DisallowNotAssignment | Disallow violations where the first usage is not an assignment |
Since: PMD 4.2
For any method that returns an array, it's a better behavior to return an empty array rather than a null reference.
This rule is defined by the following XPath expression:
//MethodDeclaration [ (./ResultType/Type[@Array='true']) and (./Block/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Literal/NullLiteral) ]
Example:
public class Example { // Not a good idea... public int []badBehavior() { // ... return null; } // Good behavior public String[] bonnePratique() { //... return new String[0]; } }
Since: PMD 4.2
If the abstract class does not provides any methods, it may be just a data container that is not to be instantiated. In this case, it's probably better to use a private or a protected constructor in order to prevent instantiation than make the class misleadingly abstract.
This rule is defined by the following XPath expression:
//ClassOrInterfaceDeclaration[ (@Abstract = 'true') and (count(//MethodDeclaration) + count(//ConstructorDeclaration) = 0) ]
Example:
public class abstract Example { String field; int otherField; }
Since: PMD 4.2
Swith are designed complex branches, and allow branches to share treatement. Using a switch for only a few branches is ill advised, as switches are not as easy to understand as if. In this case, it's most likely is a good idea to use a if statement instead, at least to increase code readability.
This rule is defined by the following XPath expression:
//SwitchStatement[ (count(.//SwitchLabel) < $minimumNumberCaseForASwitch) ]
Example:
// With a minimumNumberCaseForASwitch of 3 public class Foo { public void bar() { switch (condition) { case ONE: instruction; break; default: break; // not enough for a 'switch' stmt, a simple 'if' stmt would have been more appropriate } } }
This rule has the following properties:
Name | Default value | Description |
---|---|---|
minimumNumberCaseForASwitch | 3 | Minimum number of branches for a switch |