1

Is it good practice to instantiate collection field on declaration? For example:

class A {
    private List<String> list = new ArrayList<>();

    public List<String> getList() {
        return list;  
    }

    public setList(List<String> list) {
        this.list = list;
    }
}

The reason why I need it is avoiding of checking for null like this:

if (a.getList() != null)
Igorock
  • 2,691
  • 6
  • 28
  • 39

4 Answers4

4

It is better to avoid having a null value where possible. You can also make the field final so you know it will never be null There are annotations which allow you to trace the value can't be null.

private final List<String> list = new ArrayList<>();

@NotNull
public List<String> getList() {
    return list;  
}

if you do this later

if (a.getList() != null) // your IDE can tell you this is always true.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Opinions vary, but in this case I'd argue definitely yes: empty collections are far clearer and purer than nullable and empty-able collections.

Initialising there also means you could make the field final which confers some benefits, though here you'd have to make your setList() instead call clear() and addAll() the new items. So perhaps not much benefit in that alone here but in other cases it has advantages...

declension
  • 4,110
  • 22
  • 25
0

I believe a better place to initiate your objects is the Constructor of your class.
A comprehensive explanation : Should I instantiate instance variables on declaration or in the constructor?

Instantiating object in a constructor

Community
  • 1
  • 1
Ehsan
  • 357
  • 5
  • 22
0

With the specific code you showed, setList() can set a null value, so you cannot remove the null checks. However I would recommend you change the setter to 1) reject null values, or 2) set Collections.emptyList() instead of null, or 3) set a new ArrayList or LinkedList instead of null. null values are always a pain to deal with, and this is even worse with collections. Many best practices recommend to forbid null collections. And I woleheartedly agree.

Changing such behaviour mean you need to look at all call sites for getList () and check such change will not break it. If it does, then you need to change the solution or adapt client code.

JnRouvignac
  • 807
  • 5
  • 19