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... aArguments ) {
    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;
    //this style may help to eliminate such errors:
    //this.fName = aName;
  }

  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
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -