0

Stylistically is it better to initialise Java fields within a constructor or at the point where the field is declared? For example:

public class Foo {
  private final List<String> l;

  public Foo() {
    this.l = new LinkedList<String>();
  }
}

... or

public class Foo {
  private final List<String> l = new LinkedList<String>();
}

I have typically favoured the former as it seemed clearer. However, the latter obviously results in more compact code.

Adamski
  • 54,009
  • 15
  • 113
  • 152
  • possible duplicate of [Best Practice: Initialize class fields in constructor or at declaration?](http://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration) – Oliver Charlesworth Mar 21 '12 at 11:23
  • The former one's good to me because, your list is initialized only when your object is created. – sgowd Mar 21 '12 at 11:23
  • So is it in the second case too though. – aioobe Mar 21 '12 at 11:26

2 Answers2

4

My rule of thumb is:

Put it at the point of the declaration if

  • ...it can (i.e. if it doesn't rely on constructor arguments for instance)
  • ...it's value does not need any form of computation
  • ...the value is the same regardless which constructor is used.

otherwise, put it in the constructor.

Usually I follow the official Java Coding Conventions strictly. In this particular case the convention doesn't say anything about it, so it's up to each programmer to decide. Which ever you pick however, you probably want to be consistent with your choice.

aioobe
  • 413,195
  • 112
  • 811
  • 826
1

If you have more than one constructor then the initialisation (may) need to be repeated if it was not initialised at point of delcaration.

hmjd
  • 120,187
  • 20
  • 207
  • 252