Beware of mistaken field redeclares

Beware of this simple mistake, which can be hard to track down: if a field is mistakenly redeclared within the body of a method, then the field is not being referenced, but rather a temporary local variable with the same name.

A common symptom of this problem is that a stack trace indicates that a field is null, but a cursory examination of the code makes it seem as if the field has been correctly initialized.

Naming conventions can reduce the frequency of this error, but they cannot eliminate it.

Example

public final class MistakenRedeclare {

  public static void main(String... aArgs) {
    MistakenRedeclare mistake = new MistakenRedeclare("blah");
    //Throws NullPointerException, since the return value of
    //getName is null.
    System.out.println("Length of name: " + mistake.getName().length());
  }

  public MistakenRedeclare(String aName) {
    //Oops! Setting a local variable, not the field!
    String fName = aName;
    //should really be:
    //fName = aName; 
    //
    //if you qualify references with the 'this' keyword, 
    //then you don't need a conventional 'f' and 'a' 
    //prefixes (to distinguish field versus argument)
    //this.name = name;
  }

  public String getName(){
    return fName;
  }

  //..elided

  // PRIVATE
  private String fName;
} 

Example run of this class:

>java -cp . MistakenRedeclare
Exception in thread "main" java.lang.NullPointerException
        at MistakenRedeclare.main(MistakenRedeclare.java:7)

See Also :
Naming conventions