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.

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.