Wednesday, September 28, 2011

PMD - Design Rules

The sixth installment of explanation of PMD rules covering Design Rules

Design Rules

The Design Ruleset contains a collection of rules that find questionable designs.

UseSingleton

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. Or just simply add a private constructor to avoid this error.

Example

public class MaybeASingleton {
public static void foo() {}
public static void bar() {}
}

SimplifyBooleanReturns

Avoid unnecessary if..then..else statements when returning a boolean. This will reduce the code and it does not spoil the readability.

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;
  }
}

SimplifyBooleanExpressions

Avoid unnecessary comparisons in boolean expressions - this complicates simple code. Comparing to a true or false is not necessary. One should directly use the result.

Example

public class Bar {
// can be simplified to
// bar = isFoo();
private boolean bar = (isFoo() == true);
 
public isFoo() { return false;}
}

SwitchStmtsShouldHaveDefault

Switch statements should have a default label.

Example

public class Foo {
public void bar() {
  int x = 2;
  switch (x) {
   case 2: int j = 8;
  }
}
}

AvoidDeeplyNestedIfStmts

Deeply nested if..then statements are hard to read, understand and maintain.

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
    }
   }
  }
}
}

AvoidReassigningParameters

Reassigning values to parameters is a questionable practice. Use a temporary local variable instead.

Example

public class Foo {
private void foo(String bar) {
  bar = "something else";
}
}

SwitchDensity

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. By separating out the code to a subclass maintenance will become easier and the code would also become more readable.

Example

public class Foo {
public void bar(int x) {
   switch (x) {
     case 1: {
       // lots of statements
      break;
     } case 2: {
       // lots of statements
       break;
     }
   }
}
}

ConstructorCallsOverridableMethod

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.

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();
  }
}

AccessorClassGeneration

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.

Example

public class Outer {
void method(){
  Inner ic = new Inner();//Causes generation of accessor class
}
public class Inner {
  private Inner(){}
}
}

FinalFieldCouldBeStatic

If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime.

Example

public class Foo {
public final int BAR = 42; // this could be static and save some space
}

CloseResource

Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use. This is an extremely important check and failing to adhere to this can result in the JVM crashing over a period of time or us running out of resources (like connections from connection pool).

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();
  }
}
}

NonStaticInitializer

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.

Example

public class MyClass {
// this block gets run before any call to a constructor
{
  System.out.println("I am about to construct myself");
}
}

DefaultLabelNotLastInSwitchStmt

By convention, the default label should be the last label in a switch statement. Syntactically it is correct to have the default: label anywhere within the switch statement.

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;
  }
}
}

NonCaseLabelInSwitchStatement

A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but it is confusing. It is easy to mix up the case labels and the non-case labels.

Example

public class Foo {
void bar(int a) {
  switch (a) {
   case 1:
      // do something
      break;
   mylabel: // this is legal, but confusing!
      break;
   default:
      break;
  }
}
}

OptimizableToArrayCall

A call to Collection.toArray can use the Collection's size vs an empty Array of the desired type.

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()]);
}
}

BadComparison

Avoid equality comparisons with Double.NaN - these are likely to be logic errors.

Example

public class Bar {
boolean x = (y == Double.NaN);
}

EqualsNull

Inexperienced programmers sometimes confuse comparison concepts and use equals() to compare to null.

Example

class Bar {
   void foo() {
       String x = "foo";
       if (x.equals(null)) { // bad!
        doSomething();
       }
   }
}

ConfusingTernary

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?"

Example

public class Foo {
boolean bar(int x, int y) {
  return (x != y) ? diff : same;
}
}

InstantiationToGetClass

Avoid instantiating an object just to call getClass() on it; use the .class public member instead.

Example

public class Foo {
// Replace this
Class c = new String().getClass();
// with this:
Class c = String.class;
}

IdempotentOperations

Avoid idempotent operations - they are have no effect.

Example

public class Foo {
public void bar() {
  int x = 2;
  x = x;
}
}

SimpleDateFormatNeedsLocale

Be sure to specify a Locale when creating a new instance of SimpleDateFormat.

Example

public class Foo {
// Should specify Locale.US (or whatever)
private SimpleDateFormat sdf = new SimpleDateFormat("pattern");
}

ImmutableField

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.

Example

public class Foo {
  private int x; // could be final
  public Foo() {
      x = 7;
  }
  public void foo() {
     int a = x + 2;
  }
}

UseLocaleWithCaseConversions

When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Turkish. This will become important if the application is expected to support languages other than English.

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);
}

AvoidProtectedFieldInFinalClass

Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead.

Example

public final class Bar {
private int x;
protected int y;  // <-- Bar cannot be subclassed, so is y really private or package visible???
Bar() {}
}

AssignmentToNonFinalStatic

Identifies a possible unsafe usage of a static field.

Example

public class StaticField {
   static int x;
   public FinalFields(int y) {
    x = y; // unsafe
   }
}

MissingStaticMethodInNonInstantiatableClass

A class that has private constructors and does not have any static methods or fields cannot be used.

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() {}
}

AvoidSynchronizedAtMethodLevel

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.

Example

public class Foo {
// Try to avoid this
synchronized void foo() {
}
// Prefer this:
void bar() {
  //something
  synchronized(this) {
  }
  //something more
}
}

MissingBreakInSwitch

A switch statement without an enclosed break statement may be a bug.

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();
   }
}
}

UseNotifyAllInsteadOfNotify

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.

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();
}
}

AvoidInstanceofChecksInCatchClause

Each caught exception type should be handled in its own catch clause.

Example

try { // Avoid this
// do something
} catch (Exception ee) {
if (ee instanceof IOException) {
  cleanup();
}
}
try {  // Prefer this:
// do something
} catch (IOException ee) {
cleanup();
}

AbstractClassWithoutAbstractMethod

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 directly) a protected constructor can be provided prevent direct instantiation.

Example

public abstract class Foo {
void int method1() { ... }
void int method2() { ... }
// consider using abstract methods or removing
// the abstract modifier and adding protected constructors
}

SimplifyConditional

No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.

Example

class Foo {
void bar(Object x) {
  if (x != null && x instanceof Bar) {
   // just drop the "x != null" check
  }
}
}

CompareObjectsWithEquals

Use equals() to compare object references; avoid comparing them with ==.

Example

class Foo {
boolean bar(String a, String b) {
  return a == b;
}
}

PositionLiteralsFirstInComparisons

Position literals first in String comparisons - that way if the String is null you won't get a NullPointerException, it'll just return false.

Example

class Foo {
boolean bar(String x) {
  return x.equals("2"); // should be "2".equals(x)
}
}

UnnecessaryLocalBeforeReturn

Avoid unnecessarily creating local variables

Example

public class Foo {
    public int foo() {
      int x = doSomething();
      return x;  // instead, just 'return doSomething();'
    }
  }

NonThreadSafeSingleton

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. http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

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;
}

UncommentedEmptyMethod

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.

Example

public void doSomething() {
}

UncommentedEmptyConstructor

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.

Example

public Foo() {
  super();
}

AvoidConstantsInterface

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.

Example

public interface ConstantsInterface {
     public static final int CONSTANT1=0;
     public static final String CONSTANT2="1";
    }

UnsynchronizedStaticDateFormatter

SimpleDateFormat is not synchronized. Sun recommends 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.

Example

public class Foo {
    private static final SimpleDateFormat sdf = new SimpleDateFormat();
    void bar() {
        sdf.format(); // bad
    }
    synchronized void foo() {
        sdf.format(); // good
    }
}

PreserveStackTrace

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. Ideally one should throw the exception that one got, but if one wishes to handle a lesser number of exceptions one could create one’s own exceptions and throw these as standard exceptions. But one should be careful to wrap the actual exception in the new exception as shown below in the “good” section. This will ensure that the stack trace is preserved at the point where we finally handle the exception.

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());
        }
    }
}

UseCollectionIsEmpty

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.

Example

public class Foo {
               void good() {
               List foo = getList();
                       if (foo.isEmpty()) {
                               // blah
                       }
        }
 
            void bad() {
            List foo = getList();
                               if (foo.size() == 0) {
                                      // blah
                               }
                }
        }

ClassWithOnlyPrivateConstructorsShouldBeFinal

A class with only private constructors should be final, unless the private constructor is called by an inner class.

Example

public class Foo {  //Should be final
    private Foo() { }
}

EmptyMethodInAbstractClassShouldBeAbstract

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.

Example

public abstract class ShouldBeAbstract
                               {
                                   public Object couldBeAbstract()
                                   {
                                      // Should be abstract method ?
                                      return null;
                                       }
 
                                   public void couldBeAbstract()
                                   {
                                   }
                               }

SingularField

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.

Example

public class Foo {
    private int x;  //Why bother saving this?
    public void foo(int y) {
     x = y + 5;
     return x;
    }
}

ReturnEmptyArrayRatherThanNull

For any method that returns an array, it's a better behavior to return an empty array rather than a null reference.

Example

public class Example
            {
                // Not a good idea...
                public int []badBehavior()
                {
                    // ...
                    return null;
                }
 
                // Good behavior
                public String[] bonnePratique()
                {
                    //...
                    return new String[0];
                }
            }

AbstractClassWithoutAnyMethod

If the abstract class does not provide 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.

Example

public class abstract Example {
        String field;
        int otherField;
}

TooFewBranchesForASwitchStatement

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 an if statement instead, at least to increase code readability.

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
               }
        }
}

No comments: