Showing posts with label Static Code Checks. Show all posts
Showing posts with label Static Code Checks. Show all posts

Wednesday, September 28, 2011

PMD - Copy Paste Checks

In addition to all the Rule validation done by PMD, PMD also checks for copy paste occurrences in the code. This is by far one of the most important checks that PMD does. More the occurrences of Copy-Paste more the likelihood of errors in the code. More the occurrences of Copy Paste the more the possibility of creating errors. One would change in one place and forget in another. Also it leads to code bloat and inefficient memory usage.

One should pay close attention to these results and read Refactoring by Martin Fowler to solve the copy paste problems.

PMD - Android Rules

This is the twenty fourth installment of explanation of PMD rules covering some Android rules.

Android Rules

These rules deal with the Android SDK, mostly related to best practices. To get better results, make sure that the auxclasspath is defined for type resolution to work.

CallSuperFirst

Super should be called at the start of the method

Example

public class DummyActivity extends Activity {
    public void onCreate(Bundle bundle) {
     // missing call to super.onCreate(bundle)
     foo();
    }
   }

CallSuperLast

Super should be called at the end of the method

Example

public class DummyActivity extends Activity {
    public void onPause() {
     foo();
     // missing call to super.onPause()
    }
   }

ProtectLogD

Log.d calls should be protected by checking Config.LOGD first

Example

public class DummyActivity extends Activity {
    public void foo() {
     Log.d("TAG", "msg1"); // Bad
 
     bar();
 
     if (Config.LOGD) Log.d("TAG", "msg1"); // Good
    }
   }

ProtectLogV

Log.v calls should be protected by checking Config.LOGV first

Example

public class DummyActivity extends Activity {
    public void foo() {
     Log.v("TAG", "msg1"); // Bad
 
     bar();
 
     if (Config.LOGV) Log.v("TAG", "msg1"); // Good
    }

PMD - JSP and JSF Rules

This is the twenty third installment of explanation of PMD rules covering rules related to JSP and JSF

Basic JSF rules

Rules concerning basic JSF guidelines.

DontNestJsfInJstlIteration

Do not nest JSF component custom actions inside a custom action that iterates over its body.

Example

                           
                                       
  •                        

Basic JSP rules

Rules concerning basic JSP guidelines.

NoLongScripts

Scripts should be part of Tag Libraries, rather than part of JSP pages.

Example

NoScriptlets

Scriptlets should be factored into Tag Libraries or JSP declarations, rather than being part of JSP pages.

Example

<%
response.setHeader("Pragma", "No-cache");
%>
           
                        String title = "Hello world!";
           

NoInlineStyleInformation

Style information should be put in CSS files, not in JSPs. Therefore, don't use or tags, or attributes like "align='center'".

Example

text

NoClassAttribute

Do not use an attribute called 'class'. Use "styleclass" for CSS styles.

Example

 
Some text
 

NoJspForward

Do not do a forward from within a JSP file.

Example

IframeMissingSrcAttribute

IFrames which are missing a src element can cause security information popups in IE if you are accessing the page through SSL. See http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q261188

Example

bad example><BODY><o:p></o:p></span></p> <p class="MsoNormal"><span><iframe></iframe><o:p></o:p></span></p> <p class="MsoNormal"><span></BODY> </HTML><o:p></o:p></span></p> <p class="MsoNormal"><span><o:p> </o:p></span></p> <p class="MsoNormal"><span><HTML><title>good example><BODY><o:p></o:p></span></p> <p class="MsoNormal"><span><iframe src="foo"></iframe><o:p></o:p></span></p> <p class="MsoNormal"><span></BODY> </HTML><o:p></o:p></span></p> <h2><span>NoHtmlComments<o:p></o:p></span></h2> <p class="MsoNormal">In a production system, HTML comments increase the payload between the application server to the client, and serve little other purpose. Consider switching to JSP comments.</p> <h3><span>Example<o:p></o:p></span></h3> <p class="MsoNormal"><span><HTML><title>bad example><BODY><o:p></o:p></span></p> <p class="MsoNormal"><span><!-- HTML comment --><o:p></o:p></span></p> <p class="MsoNormal"><span></BODY> </HTML><o:p></o:p></span></p> <p class="MsoNormal"><span><o:p> </o:p></span></p> <p class="MsoNormal"><span><HTML><title>good example><BODY><o:p></o:p></span></p> <p class="MsoNormal"><span><%-- JSP comment --%><o:p></o:p></span></p> <p class="MsoNormal"><span></BODY> </HTML><o:p></o:p></span></p> <h2><span>DuplicateJspImports<o:p></o:p></span></h2> <p class="MsoNormal">Avoid duplicate import statements inside JSP's.</p> <h3><span>Example<o:p></o:p></span></h3> <p class="MsoNormal"><span><%@ page import=\"com.foo.MyClass,com.foo.MyClass\"%><o:p></o:p></span></p> <p class="MsoNormal"><span><html><body><b><img src=\"<%=Some.get()%>/foo\">xx</img>text</b></body></html><o:p></o:p></span></p> <h2><span>JspEncoding<o:p></o:p></span></h2> <p class="MsoNormal">A missing 'meta' tag or page directive will trigger this rule, as well as a non-UTF-8 charset.</p> <h3><span>Example<o:p></o:p></span></h3> <p class="MsoNormal"><span>Most browsers should be able to interpret the following headers:<o:p></o:p></span></p> <p class="MsoNormal"><span><span>                </span><o:p></o:p></span></p> <p class="MsoNormal"><span><span>                </span><%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><o:p></o:p></span></p> <p class="MsoNormal"><span><span>                    </span><o:p></o:p></span></p> <p class="MsoNormal"><span><span>               </span><span> </span><meta http-equiv="Content-Type"  content="text/html; charset=UTF-8" /><o:p></o:p></span></p><p></p></DIV>

PMD - Clone Rules

This is the twenty second installment of explanation of PMD rules covering Cloning of objects.

Clone Implementation Rules

The Clone Implementation ruleset contains a collection of rules that find questionable usages of the clone() method.
Clone is a method used to create a copy of objects in Java. The resulting object must be an exact replica of the object from which it was cloned. It is important to note that in the process of cloning if we use a statement like
this.attribute = classcloned.attribute
will only achieve a shallow copy as only the reference of the object attribute will be copied into the cloned class. Any changes to attribute in the clone will impact the original object. Instead we should use
this.attribute = classcloned.attribute,clone()
This will ensure that the cloned object gets a cloned copy of the attribute object too.

ProperCloneImplementation

Object clone() should be implemented with super.clone().

Example

class Foo{
    public Object clone(){
        return new Foo(); // This is bad
    }
}

CloneThrowsCloneNotSupportedException

The method clone() should throw a CloneNotSupportedException.

Example

public class MyClass implements Cloneable{
     public Object clone() { // will cause an error
          MyClass clone = (MyClass)super.clone();
          return clone;
     }
}

CloneMethodMustImplementCloneable

The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException.

Example

public class MyClass {
public Object clone() throws CloneNotSupportedException {
  return foo;
}
}

PMD - J2EE Rules

This is the twenty first installment of explanation of PMD rules covering J2EE Rules.

J2EE Rules

These are rules for J2EE

UseProperClassLoader

In J2EE getClassLoader() might not work as expected. Use Thread.currentThread().getContextClassLoader() instead.

Example

public class Foo {
ClassLoader cl = Bar.class.getClassLoader();
}

MDBAndSessionBeanNamingConvention

The EJB Specification state that any MessageDrivenBean or SessionBean should be suffixed by Bean.

Example

/* Proper name */
public class SomeBean implements SessionBean{}
/* Bad name */
public class MissingTheProperSuffix implements SessionBean {}

RemoteSessionInterfaceNamingConvention

Remote Home interface of a Session EJB should be suffixed by 'Home'.

Example

/* Proper name */
public interface MyBeautifulHome extends javax.ejb.EJBHome {}
/* Bad name */
public interface MissingProperSuffix extends javax.ejb.EJBHome {}

LocalInterfaceSessionNamingConvention

The Local Interface of a Session EJB should be suffixed by 'Local'.

Example

/* Proper name */
public interface MyLocal extends javax.ejb.EJBLocalObject {}
/* Bad name */
public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {}

LocalHomeNamingConvention

The Local Home interface of a Session EJB should be suffixed by 'LocalHome'.

Example

/* Proper name */
public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {}
/* Bad name */
public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {}

RemoteInterfaceNamingConvention

Remote Interface of a Session EJB should NOT be suffixed.

Example

/* Bad Session suffix */
public interface BadSuffixSession extends javax.ejb.EJBObject {}
/* Bad EJB suffix */
public interface BadSuffixEJB extends javax.ejb.EJBObject {}
/* Bad Bean suffix */
public interface BadSuffixBean extends javax.ejb.EJBObject {}

DoNotCallSystemExit

Web applications should not call System.exit(), since only the web container or the application server should stop the JVM.

Example

public class Foo {
    public void bar() {
        // NEVER DO THIS IN A APP SERVER !!!
        System.exit(0);
    }
}

StaticEJBFieldShouldBeFinal

According to the J2EE specification (p.494), an EJB should not have any static fields with write access. However, static read only fields are allowed. This ensures proper behavior especially when instances are distributed by the container on several JREs.

Example

public class SomeEJB extends EJBObject implements EJBLocalHome {
        private static int BAD_STATIC_FIELD;
 
        private static final int GOOD_STATIC_FIELD;
}

DoNotUseThreads

The J2EE specification explicitly forbid use of threads.

Example

// This is not allowed
public class UsingThread extends Thread {
 
}
// Neither this,
public class OtherThread implements Runnable {
        // Nor this ...
        public void methode() {
                Runnable thread = new Thread(); thread.run();
        }
}

PMD - Unused Code Checks

This is the twentieth installment of explanation of PMD rules covering Unused Code Checks.

Unused Code Rules

The Unused Code Ruleset contains a collection of rules that find unused code.

UnusedPrivateField

Detects when a private field is declared and/or assigned a value, but not used.

Example

public class Something {
  private static int FOO = 2; // Unused
  private int i = 5; // Unused
  private int j = 6;
  public int addOne() {
    return j++;
  }
}

UnusedLocalVariable

Detects when a local variable is declared and/or assigned, but not used.

Example

public class Foo {
public void doSomething() {
  int i = 5; // Unused
}
}

UnusedPrivateMethod

Unused Private Method detects when a private method is declared but is unused.

Example

public class Something {
private void foo() {} // unused
}

UnusedFormalParameter

Avoid passing parameters to methods or constructors and then not using those parameters.

Example

public class Foo {
private void bar(String howdy) {
  // howdy is not used
}

PMD - Type Resolution Rules

This is the nineteenth installment of explanation of PMD rules covering Type Resolution Rules.

Type Resolution Rules

These are rules which resolve java Class files for comparisson, as opposed to a String

LooseCoupling

Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead

Example

import java.util.ArrayList;
import java.util.HashSet;
public class Bar {
// Use List instead
private ArrayList list = new ArrayList();
// Use Set instead
public HashSet getFoo() {
  return new HashSet();
}
}

CloneMethodMustImplementCloneable

The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException. This version uses PMD's type resolution facilities, and can detect if the class implements or extends a Cloneable class

Example

public class MyClass {
public Object clone() throws CloneNotSupportedException {
  return foo;
}
}

UnusedImports

Avoid unused import statements. This rule will find unused on demand imports, i.e. import com.foo.*.

Example

// this is bad
import java.io.*;
public class Foo {}

SignatureDeclareThrowsException

It is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand the vague interfaces. Use either a class derived from RuntimeException or a checked exception. Junit classes are excluded.

Example

public void methodThrowingException() throws Exception {
}

PMD - Security Code Guidelines

This is the eighteenth installment of explanation of PMD rules covering some Security Guidelines.

Security Code Guidelines

These rules check the security guidelines from Sun, published at http://java.sun.com/security/seccodeguide.html#gcg

MethodReturnsInternalArray

Exposing internal arrays directly allows the user to modify some code that could be critical. It is safer to return a copy of the array.

Example

public class SecureSystem {
  UserData [] ud;
  public UserData [] getUserData() {
      // Don't return directly the internal array, return a copy
      return ud;
  }
}

ArrayIsStoredDirectly

Constructors and methods receiving arrays should clone objects and store the copy. This prevents that future changes from the user affect the internal functionality.

Example

public class Foo {
private String [] x;
  public void foo (String [] param) {
      // Don't do this, make a copy of the array at least
      this.x=param;
  }
}

PMD - String and StringBuffer Rules

This is the seventeenth installment giving details of PMD rules covering String and StringBuffer rules.

String and StringBuffer Rules

These rules deal with different problems that can occur with manipulation of the class String or StringBuffer.

AvoidDuplicateLiterals

Code containing duplicate String literals can usually be improved by declaring the String as a constant field.

Example

public class Foo {
private void bar() {
    buz("Howdy");
    buz("Howdy");
    buz("Howdy");
    buz("Howdy");
}
private void buz(String x) {}
}

StringInstantiation

Avoid instantiating String objects; this is usually unnecessary.

Example

public class Foo {
private String bar = new String("bar"); // just do a String bar = "bar";
}

StringToString

Avoid calling toString() on String objects; this is unnecessary.

Example

public class Foo {
private String baz() {
  String bar = "howdy";
  return bar.toString();
}
}

InefficientStringBuffering

Avoid concatenating non literals in a StringBuffer constructor or append().

Example

public class Foo {
void bar() {
  // Avoid this
  StringBuffer sb=new StringBuffer("tmp = "+System.getProperty("java.io.tmpdir"));
  // use instead something like this
  StringBuffer sb = new StringBuffer("tmp = ");
  sb.append(System.getProperty("java.io.tmpdir"));
}
}

UnnecessaryCaseChange

Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()

Example

public class Foo {
  public boolean bar(String buz) {
    // should be buz.equalsIgnoreCase("baz")
    return buz.toUpperCase().equals("baz");
    // another unnecessary toUpperCase()
    // return buz.toUpperCase().equalsIgnoreCase("baz");
  }
}

UseStringBufferLength

Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals("") or StringBuffer.toString().length() ==.

Example

public class Foo {
void bar() {
  StringBuffer sb = new StringBuffer();
  // this is bad
  if(sb.toString().equals("")) {}
  // this is good
  if(sb.length() == 0) {}
}
}

AppendCharacterWithChar

Avoid concatenating characters as strings in StringBuffer.append.

Example

public class Foo {
void bar() {
  StringBuffer sb=new StringBuffer();
  // Avoid this
  sb.append("a");
 
  // use instead something like this
  StringBuffer sb=new StringBuffer();
  sb.append('a');
}
}

ConsecutiveLiteralAppends

Consecutively calling StringBuffer.append with String literals

Example

public class Foo {
private void bar() {
   StringBuffer buf = new StringBuffer();
   buf.append("Hello").append(" ").append("World"); //bad
   buf.append("Hello World");//good
}
}

UseIndexOfChar

Use String.indexOf(char) when checking for the index of a single character; it executes faster.

Example

public class Foo {
void bar() {
  String s = "hello world";
  // avoid this
  if (s.indexOf("d") {}
  // instead do this
  if (s.indexOf('d') {}
}
}

InefficientEmptyStringCheck

String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String object just to check its size. Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found.

Example

public class Foo {
    void bar(String string) {
        if (string != null && string.trim().size() > 0) {
                   doSomething();
       }
    }
}

InsufficientStringBufferDeclaration

Failing to pre-size a StringBuffer properly could cause it to re-size many times during runtime. This rule checks the characters that are actually passed into StringBuffer.append(), but represents a best guess "worst case" scenario. An empty StringBuffer constructor initializes the object to 16 characters. This default is assumed if the length of the constructor can not be determined.

Example

public class Foo {
    void bar() {
        StringBuffer bad = new StringBuffer();
        bad.append("This is a long string, will exceed the default 16 characters");//bad
        StringBuffer good = new StringBuffer(41);
        good.append("This is a long string, which is pre-sized");//good
    }
}

UselessStringValueOf

No need to call String.valueOf to append to a string; just use the valueOf() argument directly.

Example

public String convert(int i) {
  String s;
  s = "a" + String.valueOf(i); // Bad
  s = "a" + i; // Better
  return s;
}

StringBufferInstantiationWithChar

StringBuffer sb = new StringBuffer('c'); The char will be converted into int to intialize StringBuffer size.

Example

class Foo {
  StringBuffer sb1 = new StringBuffer('c'); //Bad. This is wrong, not bad.
  StringBuffer sb2 = new StringBuffer("c"); //Better
}

UseEqualsToCompareStrings

Using '==' or '!=' to compare strings only works if intern version is used on both sides

Example

class Foo {
  boolean test(String s) {
    if (s == "one") return true; //Bad
    if ("two".equals(s)) return true; //Better
    return false;
  }
}

AvoidStringBufferField

StringBuffers can grow quite a lot, and so may become a source of memory leak (if the owning class has a long life time).

Example

class Foo {
        private StringBuffer memoryLeak;
}

PMD - Strict Exception Rules

The sixteenth installment of explanation of PMD rules covering Strict Exception Rules

Strict Exception Rules

These rules provide some strict guidelines about throwing and catching exceptions.

AvoidCatchingThrowable

This is dangerous because it casts too wide a net; it can catch things like OutOfMemoryError.

Example

public class Foo {
public void bar() {
  try {
   // do something
  } catch (Throwable th) {  //Should not catch throwable
   th.printStackTrace();
  }
}
}

SignatureDeclareThrowsException

It is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand the vague interfaces. Use either a class derived from RuntimeException or a checked exception.

Example

public void methodThrowingException() throws Exception {
}

ExceptionAsFlowControl

Using Exceptions as flow control leads to GOTOish code and obscures true exceptions when debugging.

Example

public class Foo {
void bar() {
  try {
   try {
   } catch (Exception e) {
    throw new WrapperException(e);
    // this is essentially a GOTO to the WrapperException catch block
   }
  } catch (WrapperException e) {
   // do some more stuff
  }
}
}

AvoidCatchingNPE

Code should never throw NPE under normal circumstances. A catch block may hide the original error, causing other more subtle errors in its wake.

Example

public class Foo {
void bar() {
  try {
   // do something
   }  catch (NullPointerException npe) {
  }
}
}

AvoidThrowingRawExceptionTypes

Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead.

Example

public class Foo {
public void bar() throws Exception {
  throw new Exception();
}
}

AvoidThrowingNullPointerException

Avoid throwing a NullPointerException - it's confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly seen as a programmer-initiated exception.

Example

public class Foo {
void bar() {
  throw new NullPointerException();
}
}

AvoidRethrowingException

Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.

Example

public class Foo {
   void bar() {
    try {
    // do something
    }  catch (SomeException se) {
       throw se;
    }
   }
  }

DoNotExtendJavaLangError

Errors are system exceptions. Do not extend them.

Example

public class Foo extends Error { }

DoNotThrowExceptionInFinally

Throwing exception in a finally block is confusing. It may mask exception or a defect of the code, it also render code cleanup uninstable. Note: This is a PMD implementation of the Lint4j rule "A throw in a finally block"

Example

public class Foo {
        public void bar() {
               try {
                       // Here do some stuff
               }
               catch( Exception e) {
                       // Handling the issue
               }
               finally {
                       // is this really a good idea?
                       throw new Exception();
               }
        }
}

AvoidThrowingNewInstanceOfSameException

Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to code size and runtime complexity.

Example

public class Foo {
     void bar() {
      try {
       // do something
      }  catch (SomeException se) {
         // harmless comment      
           throw new SomeException(se);
      }
     }
    }

PMD - Optimization Rules

This is the fifteenth installment of explanation of PMD rules covering Optimization Rules. These rules will ensure that we get optimum performance from the applications.

Optimization Rules

These rules deal with different optimizations that generally apply to performance best practices.

LocalVariableCouldBeFinal

A local variable assigned only once can be declared final.

Example

public class Bar {
public void foo () {
  String a = "a"; //if a will not be assigned again it is better to do this:
  final String b = "b";
}
}

MethodArgumentCouldBeFinal

A method argument that is never assigned can be declared final. This will ensure that the value is not changed inadvertently in future.

Example

public void foo (String param) {
  // do stuff with param never assigning it
  // better: public void foo (final String param) {
}

AvoidInstantiatingObjectsInLoops

Detects when a new object is created inside a loop. There will be situations where this will be unavoidable and so this rule can be violated when required.

Example

public class Something {
  public static void main( String as[] ) {  
    for (int i = 0; i < 10; i++) {
      Foo f = new Foo(); //Avoid this whenever you can it's really expensive
    }
  }
}

UseArrayListInsteadOfVector

ArrayList is a much better Collection implementation than Vector.

Example

public class SimpleTest extends TestCase {
public void testX() {
  Collection c = new Vector();
  // This achieves the same with much better performance
  // Collection c = new ArrayList();
}
}

SimplifyStartsWith

Since it passes in a literal of length 1, this call to String.startsWith can be rewritten using String.charAt(0) to save some time.

Example

public class Foo {
  boolean checkIt(String x) {
      return x.startsWith("a");
  }
}

UseStringBufferForStringAppends

Finds usages of += for appending strings. This greatly improves the performance. Better still it is sure that the variable will be accessed by only one thread then it is better to use StringBuilder as the methods of this class are not synchronized. The StringBuffer should be used only if we expect to be appending to the buffer from multiple threads.

Example

public class Foo {
void bar() {
  String a;
  a = "foo";
  a += " bar";
  // better would be:
  // StringBuffer a = new StringBuffer("foo");
  // a.append(" bar);
}
}

UseArraysAsList

The java.util.Arrays class has a "asList" method that should be used when you want to create a new List from an array of objects. It is faster than executing a loop to copy all the elements of the array one by one

Example

public class Test {
    public void foo(Integer[] ints) {
    // could just use Arrays.asList(ints)
     List l= new ArrayList(10);
     for (int i=0; i< 100; i++) {
      l.add(ints[i]);
     }
     for (int i=0; i< 100; i++) {
      l.add(a[i].toString()); // won't trigger the rule
     }
    }
   }

AvoidArrayLoops

Instead of copying data between two arrays, use System.arraycopy method

Example

public class Test {
public void bar() {
  int[] a = new int[10];
  int[] b = new int[10];
  for (int i=0;i <10;i++) {
   b[i]=a[i];
  }
}
}
            // this will trigger the rule
            for (int i=0;i<10;i++) {
             b[i]=a[c[i]];
            }
 
        }
    }

UnnecessaryWrapperObjectCreation

Parsing method should be called directly instead.

Example

public int convert(String s) {
  int i, i2;
 
  i = Integer.valueOf(s).intValue(); // this wastes an object
  i = Integer.parseInt(s); // this is better
 
  i2 = Integer.valueOf(i).intValue(); // this wastes an object
  i2 = i; // this is better
 
  String s3 = Integer.valueOf(i2).toString(); // this wastes an object
  s3 = Integer.toString(i2); // this is better
 
  return i2;
}

AddEmptyString

Finds empty string literals which are being added. This is an inefficient way to convert any type to a String.

Example

String s = "" + 123; // bad 
        String t = Integer.toString(456); // ok

PMD - Naming Rules

This is the fourteenth installment of explanation of PMD rules covering Naming Rules. This covers details of how the variables, classes, packages should be named to follow a standard pattern.

Naming Rules

The Naming Ruleset contains a collection of rules about names - too long, too short, and so forth.

ShortVariable

Detects when a field, local, or parameter has a very short name. It is preferable to avoid variables like “I” “j” “k” as it reduces the understandability of the code. Using proper names makes it easier to understand the purpose of the variable. Although it is OK to use such variables for looping, it can get confusing if one has nested looping.

Example

public class Something {
  private int q = 15; // VIOLATION - Field
  public static void main( String as[] ) {  // VIOLATION - Formal
    int r = 20 + q; // VIOLATION - Local
    for (int i = 0; i < 10; i++) { // Not a Violation (inside FOR)
      r += q;
    }
  }
}

LongVariable

Detects when a field, formal or local variable is declared with a long name.

Example

public class Something {
  int reallyLongIntName = -3;  // VIOLATION - Field
  public static void main( String argumentsList[] ) { // VIOLATION - Formal
    int otherReallyLongName = -5; // VIOLATION - Local
    for (int interestingIntIndex = 0;  // VIOLATION - For
            interestingIntIndex < 10;
             interestingIntIndex ++ ) {
    }
}

ShortMethodName

Detects when very short method names are used. Similar to variables methods should have meaningful names.

Example

public class ShortMethod {
  public void a( int i ) { // Violation
  }
}

VariableNamingConventions

A variable naming conventions rule - customize this to your liking. Currently, it checks for final variables that should be fully capitalized and non-final variables that should not include underscores.

Example

public class Foo {
public static final int MY_NUM = 0;
public String myTest = "";
DataModule dmTest = new DataModule();
}

MethodNamingConventions

Method names should always begin with a lower case character, and should not contain underscores.

Example

public class Foo {
public void fooStuff() {
}
}

ClassNamingConventions

Class names should always begin with an upper case character.

Example

public class Foo {}

AbstractNaming

Abstract classes should be named 'AbstractXXX'.

Example

public abstract class Foo { // should be AbstractFoo
}

AvoidDollarSigns

Avoid using dollar signs in variable/method/class/interface names.

Example

public class Fo$o {  // yikes!
}

MethodWithSameNameAsEnclosingClass

Non-constructor methods should not have the same name as the enclosing class.

Example

public class MyClass {
// this is bad because it is a method
public void MyClass() {}
// this is OK because it is a constructor
public MyClass() {}
}

SuspiciousHashcodeMethodName

The method name and return type are suspiciously close to hashCode(), which may mean you are intending to override the hashCode() method.

Example

public class Foo {
public int hashcode() {
// oops, this probably was supposed to be hashCode
}
}

SuspiciousConstantFieldName

A field name is all in uppercase characters, which in Sun's Java naming conventions indicate a constant. However, the field is not final.

Example

public class Foo {
// this is bad, since someone could accidentally
// do PI = 2.71828; which is actualy e
// final double PI = 3.16; is ok
double PI = 3.16;
}

SuspiciousEqualsMethodName

The method name and parameter number are suspiciously close to equals(Object), which may mean you are intending to override the equals(Object) method.

Example

public class Foo {
public int equals(Object o) {
// oops, this probably was supposed to be boolean equals
}
public boolean equals(String s) {
// oops, this probably was supposed to be equals(Object)
}
}

AvoidFieldNameMatchingTypeName

It is somewhat confusing to have a field name matching the declaring class name. This probably means that type and or field names could be more precise.

Example

public class Foo extends Bar {
// There's probably a better name for foo
int foo;
}

AvoidFieldNameMatchingMethodName

It is somewhat confusing to have a field name with the same name as a method. While this is totally legal, having information (field) and actions (method) is not clear naming.

Example

public class Foo {
        Object bar;
        // bar is data or an action or both?
        void bar() {
        }
}

NoPackage

Detects when a class or interface does not have a package definition.

Example

// no package declaration
public class ClassInDefaultPackage {
}

PackageCase

Detects when a package definition contains upper case characters.

Example

package com.MyCompany;  // <- should be lower case name
public class SomeClass {
}

MisleadingVariableName

Detects when a non-field has a name starting with 'm_'. This usually indicates a field and thus is confusing.

Example

public class Foo {
    private int m_foo; // OK
    public void bar(String m_baz) {  // Bad
      int m_boz = 42; // Bad
    }
  }

BooleanGetMethodName

Looks for methods named 'getX()' with 'boolean' as the return type. The convention is to name these methods 'isX()'.

Example

public boolean getFoo(); // bad
public boolean isFoo(); // ok
public boolean getFoo(boolean bar); // ok, unless checkParameterizedMethods=true

PMD - Migration Rules

The thirteenth installation of explanation of PMD rules covering Migration Rules. These rules cover the changes that need to be done by developers when moving from older versions of JDK (1.3, 1.4) to the newer versions of Java.

Migration Rules

Contains rules about migrating from one JDK version to another. Don't use these rules directly, rather, use a wrapper ruleset such as migrating_to_13.xml.

ReplaceVectorWithList

Consider replacing Vector usages with the newer java.util.ArrayList if expensive threadsafe operation is not required.

Example

public class Foo {
void bar() {
    Vector v = new Vector();
}
}

ReplaceHashtableWithMap

Consider replacing this Hashtable with the newer java.util.Map

Example

public class Foo {
     void bar() {
        Hashtable h = new Hashtable();
     }
    }

ReplaceEnumerationWithIterator

Consider replacing this Enumeration with the newer java.util.Iterator

Example

public class Foo implements Enumeration {
    private int x = 42;
    public boolean hasMoreElements() {
        return true;
    }
    public Object nextElement() {
        return String.valueOf(i++);
    }
}

AvoidEnumAsIdentifier

Finds all places where 'enum' is used as an identifier.

Example

public class A {
        public  class foo {
            String enum = "foo";
        }
    }

AvoidAssertAsIdentifier

Finds all places where 'assert' is used as an identifier.

Example

public class A {
        public  class foo {
            String assert = "foo";
        }
    }

IntegerInstantiation

In JDK 1.5, calling new Integer() causes memory allocation. Integer.valueOf() is more memory friendly. Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

Example

public class Foo {
private Integer i = new Integer(0); // change to Integer i = Integer.valueOf(0);
}

ByteInstantiation

In JDK 1.5, calling new Byte() causes memory allocation. Byte.valueOf() is more memory friendly.

Example

public class Foo {
private Byte i = new Byte(0); // change to Byte i =
Byte.valueOf(0);
}

ShortInstantiation

In JDK 1.5, calling new Short() causes memory allocation. Short.valueOf() is more memory friendly.

Example

public class Foo {
private Short i = new Short(0); // change to Short i =
Short.valueOf(0);
}

LongInstantiation

In JDK 1.5, calling new Long() causes memory allocation. Long.valueOf() is more memory friendly.

Example

public class Foo {
private Long i = new Long(0); // change to Long i =
Long.valueOf(0);
}

JUnit4TestShouldUseBeforeAnnotation

In JUnit 3, the setUp method was used to set up all data entities required in running tests. JUnit 4 skips the setUp method and executes all methods annotated with @Before before all tests

Example

public class MyTest {
    public void setUp() {
        bad();
    }
}
public class MyTest2 {
    @Before public void setUp() {
        good();
    }
}

JUnit4TestShouldUseAfterAnnotation

In JUnit 3, the tearDown method was used to clean up all data entities required in running tests. JUnit 4 skips the tearDown method and executes all methods annotated with @After after running each test

Example

public class MyTest {
    public void tearDown() {
        bad();
    }
}
public class MyTest2 {
    @After public void tearDown() {
        good();
    }
}

JUnit4TestShouldUseTestAnnotation

In JUnit 3, the framework executed all methods which started with the word test as a unit test. In JUnit 4, only methods annotated with the @Test annotation are executed.

Example

public class MyTest {
    public void testBad() {
        doSomething();
    }
 
        @Test
    public void testGood() {
        doSomething();
    }
}

JUnit4SuitesShouldUseSuiteAnnotation

In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated through the @RunWith(Suite.class) annotation.

Example

public class BadExample extends TestCase{
 
    public static Test suite(){
        return new Suite();
    }
}
 
@RunWith(Suite.class)
@SuiteClasses( { TestOne.class, TestTwo.class })
public class GoodTest {
}

JUnitUseExpected

Example

public class MyTest {
        @Test
    public void testBad() {
        try {
            doSomething();
            fail("should have thrown an exception");
        } catch (Exception e) {
        }
    }
 
        @Test(expected=Exception.class)
    public void testGood() {
        doSomething();
    }
}

PMD - Java Logging Rules

The twelfth installment of explanation of PMD rules covering Java Logging Rules.

Java Logging Rules

The Java Logging ruleset contains a collection of rules that find questionable usages of the logger.

MoreThanOneLogger

Normally only one logger is used in each class.

Example

class Foo{
    Logger log = Logger.getLogger(Foo.class.getName());
    // It is very rare to see two loggers on a class, normally
    // log information is multiplexed by levels
    Logger log2= Logger.getLogger(Foo.class.getName());
}

LoggerIsNotStaticFinal

In most cases, the Logger can be declared static and final.

Example

class Foo{
    Logger log = Logger.getLogger(Foo.class.getName());
    // It is much better to declare the logger as follows 
    // static final Logger log = Logger.getLogger(Foo.class.getName());
}

SystemPrintln

System.(out|err).print is used, consider using a logger.

Example

class Foo{
    Logger log = Logger.getLogger(Foo.class.getName());
    public void testA () {
        System.out.println("Entering test");
        // Better use this
        log.fine("Entering test");
    }
}

AvoidPrintStackTrace

Avoid printStackTrace(); use a logger call instead.

Example

class Foo {
void bar() {
  try {
   // do something
  } catch (Exception e) {
   e.printStackTrace();
  }
}
}

PMD - Jakarta Commons Logging Rules

The eleventh installation of explanation of PMD rules covering Jakarta Common Logging Rules.

Jakarta Commons Logging Rules

The Jakarta Commons Logging ruleset contains a collection of rules that find questionable usages of that framework.

UseCorrectExceptionLogging

To make sure the full stacktrace is printed out, use the logging statement with 2 arguments: a String and a Throwable.

Example

public class Main {
private static final Log _LOG = LogFactory.getLog( Main.class );
void bar() {
  try {
  } catch( Exception e ) {
   _LOG.error( e ); //Wrong!
  } catch( OtherException oe ) {
   _LOG.error( oe.getMessage(), oe ); //Correct
  }
}
}

ProperLogger

A logger should normally be defined private static final and have the correct class. Private final Log log; is also allowed for rare cases where loggers need to be passed around, with the restriction that the logger needs to be passed into the constructor.

Example

public class Foo {
// right
  private static final Log LOG = LogFactory.getLog(Foo.class);
// wrong
protected Log LOG = LogFactory.getLog(Testclass.class);
}

PMD - JUnit Rules

The tenth installment of explanation of PMD rules covering JUnit rules.

JUnit Rules

These rules deal with different problems that can occur with JUnit tests.

JUnitStaticSuite

The suite() method in a JUnit test needs to be both public and static.

Example

import junit.framework.*;
public class Foo extends TestCase {
public void suite() {} // oops, should be static
private static void suite() {} // oops, should be public
}

JUnitSpelling

Some JUnit framework methods are easy to misspell.

Example

import junit.framework.*;
public class Foo extends TestCase {
public void setup() {} // oops, should be setUp
public void TearDown() {} // oops, should be tearDown
}

JUnitAssertionsShouldIncludeMessage

JUnit assertions should include a message - i.e., use the three argument version of assertEquals(), not the two argument version.

Example

public class Foo extends TestCase {
public void testSomething() {
  assertEquals("foo", "bar");
  // Use the form:
  // assertEquals("Foo does not equals bar", "foo", "bar");
  // instead
}
}

JUnitTestsShouldIncludeAssert

JUnit tests should include at least one assertion. This makes the tests more robust, and using assert with messages provide the developer a clearer idea of what the test does.

Example

public class Foo extends TestCase {
  public void testSomething() {
      Bar b = findBar();
  // This is better than having a NullPointerException
  // assertNotNull("bar not found", b);
  b.work();
  }
}

TestClassWithoutTestCases

Test classes end with the suffix Test. Having a non-test class with that name is not a good practice, since most people will assume it is a test case. Test classes have test methods named testXXX.

Example

//Consider changing the name of the class if it is not a test
//Consider adding test methods if it is a test
public class CarTest {
   public static void main(String[] args) {
    // do something
   }
   // code
}

UnnecessaryBooleanAssertion

A JUnit test assertion with a boolean literal is unnecessary since it always will eval to the same thing. Consider using flow control (in case of assertTrue(false) or similar) or simply removing statements like assertTrue(true) and assertFalse(false). If you just want a test to halt, use the fail method.

Example

public class SimpleTest extends TestCase {
public void testX() {
  // Why on earth would you write this?
  assertTrue(true);
}
}

UseAssertEqualsInsteadOfAssertTrue

This rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like assertEquals.

Example

public class FooTest extends TestCase {
void testCode() {
  Object a, b;
  assertTrue(a.equals(b)); // bad usage
  assertEquals("a should equals b", a, b); // good usage
}
}

UseAssertSameInsteadOfAssertTrue

This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertSame, assertNotSame.

Example

public class FooTest extends TestCase {
void testCode() {
  Object a, b;
  assertTrue(a==b); // bad usage
  assertSame(a, b);  // good usage
}
}

UseAssertNullInsteadOfAssertTrue

This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertNull, assertNotNull.

Example

public class FooTest extends TestCase {
  void testCode() {
   Object a = doSomething();
   assertTrue(a==null); // bad usage
   assertNull(a);  // good usage
   assertTrue(a != null); // bad usage
   assertNotNull(a);  // good usage
  }
}

SimplifyBooleanAssertion

Avoid negation in an assertTrue or assertFalse test. For example, rephrase: assertTrue(!expr); as: assertFalse(expr);

Example

public class SimpleTest extends TestCase {
public void testX() {
  assertTrue("not empty", !r.isEmpty()); // replace with assertFalse("not empty", r.isEmpty())
  assertFalse(!r.isEmpty()); // replace with assertTrue(r.isEmpty())
}
}

PMD - Java Bean Rules

The ninth installment of explanation of PMD rules covering Java Bean Rules

JavaBean Rules

The JavaBeans Ruleset catches instances of bean rules not being followed.

BeanMembersShouldSerialize

If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializable. Member variables need to be marked as transient, static, or have accessor methods in the class. Marking variables as transient is the safest and easiest modification. Accessor methods should follow the Java naming conventions, i.e.if you have a variable foo, you should provide getFoo and setFoo methods.

Example

  private transient int someFoo;//good, it's transient
  private static int otherFoo;// also OK
  private int moreFoo;// OK, has proper accessors, see below
  private int badFoo;//bad, should be marked transient
 
 
  private void setMoreFoo(int moreFoo){
        this.moreFoo = moreFoo;
  }
 
  private int getMoreFoo(){
        return this.moreFoo;
  }

MissingSerialVersionUID

Classes that are serializable should provide a serialVersionUID field. This is important for classes where the serialized classes can be stored for a long period of time. If in the meantime the version of the class changes and the older serialized versions cannot be deserialized then changing this variable to a different value will help.

Example

public class Foo implements java.io.Serializable {
String name;
// Define serialization id to avoid serialization related bugs
// i.e., public static final long serialVersionUID = 4328743;
}

PMD - Import Rules

The eighth installments of explanation of PMD rules covering Import rules

Import Statement Rules

These rules deal with different problems that can occur with a class' import statements.

DuplicateImports

Avoid duplicate import statements.

Example

import java.lang.String;
import java.lang.*;
public class Foo {}

DontImportJavaLang

Avoid importing anything from the package 'java.lang'. These classes are automatically imported (JLS 7.5.3).

Example

// this is bad
import java.lang.String;
public class Foo {}
 
// --- in another source code file...
 
// this is bad
import java.lang.*;
 
public class Foo {}

UnusedImports

Avoid unused import statements.

Example

// this is bad
import java.io.File;
public class Foo {}

ImportFromSamePackage

No need to import a type that lives in the same package.

Example

package foo;
import foo.Buz; // no need for this
import foo.*; // or this
public class Bar{}

TooManyStaticImports

If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from (Sun 1.5 Language Guide).

Example

import static Lennon;
import static Ringo;
import static George;
import static Paul;
import static Yoko; // Too much !

PMD - Finalizer Rules

The Seventh installment of explanation of PMD checks covering Finalizer Rules.

Finalizer Rules

These rules deal with different problems that can occur with finalizers. Finalizer methods are to be used to clean up any resource that needs to be cleaned up when the object is Garbage Collected.

EmptyFinalizer

If the finalize() method is empty, then it does not need to exist.

Example

public class Foo {
   protected void finalize() {}
}

FinalizeOnlyCallsSuperFinalize

If the finalize() is implemented, it should do something besides just calling super.finalize().

Example

public class Foo {
   protected void finalize() {
     super.finalize();
   }
}

FinalizeOverloaded

Methods named finalize() should not have parameters. It is confusing and probably a bug to overload finalize(). It will not be called by the VM.

Example

public class Foo {
   // this is confusing and probably a bug
   protected void finalize(int a) {
   }
}

FinalizeDoesNotCallSuperFinalize

If the finalize() is implemented, its last action should be to call super.finalize.

Example

public class Foo {
   protected void finalize() {
       something();
       // neglected to call super.finalize()
   }
}

FinalizeShouldBeProtected

If you override finalize(), make it protected. If you make it public, other classes may call it.

Example

public class Foo {
public void finalize() {
  // do something
}
}

AvoidCallingFinalize

Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Example

public class Foo {
void foo() {
  Bar b = new Bar();
  b.finalize();
}
}

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