Wednesday, September 28, 2011

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

No comments: