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.

2
  • 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. Commented Aug 23, 2013 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". Commented Aug 23, 2013 at 12:24

1 Answer 1

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.

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

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.