Initializing fields to 0-false-null is redundant

One of the most fundamental aspects of a programming language is how it initializes data. For Java, this is defined explicitly in the language specification. For fields and array components, when items are created, they are automatically set to the following default values by the system:

This means that explicitly setting fields to 0, false, or null (as the case may be) is unnecessary and redundant. Since this language feature was included in order to, in part, reduce repetitive coding, it's a good idea to take full advantage of it. Insisting that fields should be explicitly initialized to 0, false, or null is an idiom which is likely inappropriate to the Java programming language.

Furthermore, setting a field explicitly to 0, false, or null may even cause the same operation to be performed twice (depending on your compiler).

Example


public final class Quark {

  public Quark(String aName, double aMass){
    fName = aName;
    fMass = aMass;
  }

  //PRIVATE

  //WITHOUT redundant initialization to default values
  //private String fName;
  //private double fMass;

  //WITH redundant initialization to default values
  private String fName = null;
  private double fMass = 0.0d;
} 


If the bytecode of the Quark class is examined, the duplicated operations become clear (here, Oracle's javac compiler was used):
 
WITHOUT redundant init WITH redundant init
>javap -c -classpath . Quark
Compiled from Quark.java
public final class Quark extends java.lang.Object {
    public Quark(java.lang.String,double);
}

Method Quark(java.lang.String,double)
   0 aload_0
   1 invokespecial #1 <Method java.lang.Object()>
   4 aload_0
   5 aload_1
   6 putfield #2 <Field java.lang.String fName>
   9 aload_0
  10 dload_2
  11 putfield #3 <Field double fMass>
  14 return

>javap -c -classpath . Quark
Compiled from Quark.java
public final class Quark extends java.lang.Object {
    public Quark(java.lang.String,double);
}

Method Quark(java.lang.String,double)
   0 aload_0
   1 invokespecial #1 <Method java.lang.Object()>
   4 aload_0
   5 aconst_null
   6 putfield #2 <Field java.lang.String fName>
   9 aload_0
  10 dconst_0
  11 putfield #3 <Field double fMass>
  14 aload_0
  15 aload_1
  16 putfield #2 <Field java.lang.String fName>
  19 aload_0
  20 dload_2
  21 putfield #3 <Field double fMass>
  24 return


See Also :
Constructors in general
Don't declare local variables before use
Examine bytecode
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 -