0

Please note that: I have read some where that when we define the class level variables: List or Map. They should be always initialize with new operator: example -- private List students = new ArrayList(); But the architect is against it and telling me that it will consume 10 buckets on initializing variable on class level. But, I am very much against it: to check student list as null, before using it.

Please advice me best practice; should I initialize array list on class level or not.

Please advice. If you have any better reference URL or book name for java coding practice please provide me.

  • There's no absolutely definitive right or wrong answer; it depends on how you use your class. How often is it instantiated? Is this `List` always accessed, or very rarely? The default answer is to make the code as simple as possible and initialize with the declaration until you have clear evidence that it's presenting a problem for memory or performance. – chrylis -cautiouslyoptimistic- Aug 23 '13 at 12:21
  • Another consideration: you may want to be able to differentiate in your logic between "nothing outside the class has initialized this list yet" and "this list is empty". – Michelle Aug 23 '13 at 12:24

1 Answers1

1

Your question does not hold enough information to make the final verdict.

If your overall program is such that you have countless list and map variables, but each specific run only uses a few of them, then there is a case for lazy initialization. This is exceedingly rare in practice, however.

Personally, I always prefer private final variables to hold container-typed objects (list, map, set). Clear code, no bugs, less redundant checks (as you note), thread-safe (at least as far as publishing is concerned).

There are many pitfalls to lazy initialization and, lacking good arguments against it, eager initialization is generally the recommended best practice.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436