Should I keep instance variables in Java always initialized or not?

I recently started a new project, and I try to ensure that my instance variables are always initialized to some value, so none of them are equal to zero at any time. Below is a small example:

public class ItemManager {

  ItemMaster itemMaster;
  List<ItemComponentManager> components;

  ItemManager() {
    itemMaster = new ItemMaster();
    components = new ArrayList<ItemComponentManager>();
  }

  ...
}

The point is basically to avoid the tedious checking of zero before using an instance variable somewhere in the code. So far, it worked well, and you basically don't need a null value, since you can also check for an empty string or empty list, etc. I do not use this approach for variables with a limited range, since their scope is very limited, and therefore does not affect other parts of the code.

, , , - , . , ?

+5
12

- :

, , . , , .

, /. final, . , , .

+9

, private, !

- " ", :

class Foo {
    private List<X> stuff;
    public void add(X x) {
        if (stuff == null)
            stuff = new ArrayList<X>();
        stuff.add(x);
    }
    public List<X> getStuff() {
        if (stuff == null)
            return Collections.emptyList();
        return Collections.unmodifiableList(stuff);
    }
}

( Collections.unmodifiableList - , / , )

, . , ( ), , .

, , .

DI/IOC, , ( , ) -

+4

, - , , "" placeholder, .

, , . , , undefined.

, . , null . - , , - .

+3

final, . .

, null. , null , .

+2

, . , , , . , null. , , - - .

:

public class ItemManager {

  ItemMaster itemMaster = new ItemMaster();
  List<ItemComponentManager> components = new ArrayList<ItemComponentManager>();

  ItemManager() {
     ...
  }
  ...
}
+2

, , , , , ( , ). "", .

... , , , :

  private final ItemMaster itemMaster;
  private final List components;

  // instance initialization block - happens at construction time
  {
      itemMaster = new ItemMaster();
      components = new ArrayList();
  }

, null, ( , ).

+2

, .

+1

, - .

null. API Java null.

, , , , .

+1

100% . . - - .

DRY . , .

+1

,

itemMaster = null; 

ItemManager - itemMaster null. ( ItemManager ..)

, .

0

, . , , . , null. , PITA, .

0

"ItemManager" ItemManager - . , , , . - Spring (http://www.springsource.org/), ItemComponentManagers ItemManager.

Without DI, manual initialization in serious applications is a nightmare for debugging and connecting the various "manager" classes to make narrow tests hellish.

Always use DI (even when building tests). For data objects, create a get () method that creates a list if it does not exist. However, if the object is complex, it will almost certainly find your life better using the Factory or Builder template, and set the F / B member variables if necessary.

0
source

All Articles