Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I recently started a new project and I'm trying to keep my instance variables always initialized to some value, so none of them is at any time null. Small example below:

public class ItemManager {

  ItemMaster itemMaster;
  List<ItemComponentManager> components;

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

  ...
}

The point is mainly to avoid the tedious checking for null before using an instance variable somewhere in the code. So far, it's working good and you mostly don't need the null-value as you can check also for empty string or empty list, etc. I'm not using this approach for method scoped variables as their scope is very limited and so doesn't affect other parts of the code.

This all is kind of experimental, so I'd like to know if this approach could work or if there are some pitfalls which I'm not seeing yet. Is it generally a good idea to keep instance variables initialized?

like image 665
MicSim Avatar asked Feb 13 '09 09:02

MicSim


2 Answers

I usually treat an empty collection and a null collection as two separate things:

An empty collection implies that I know there are zero items available. A null collection will tell me that I don't know the state of the collection, which is a different thing.

So I really do not think it's an either/or. And I would declare the variable final if I initialize them in the constructor. If you declare it final it becomes very clear to the reader that this collection cannot be null.

like image 184
krosenvold Avatar answered Sep 24 '22 19:09

krosenvold


First and foremost, all non-final instance variables must be declared private if you want to retain control!

Consider lazy instantiation as well -- this also avoids "bad state" but only initializes upon use:

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);
    }
}

(Note the use of Collections.unmodifiableList -- unless you really want a caller to be able to add/remove from your list, you should make it immutable)

Think about how many instances of the object in question will be created. If there are many, and you always create the lists (and might end up with many empty lists), you could be creating many more objects than you need.

Other than that, it's really a matter of taste and if you can have meaningful values when you construct.

If you're working with a DI/IOC, you want the framework to do the work for you (though you could do it through constructor injection; I prefer setters) -- Scott

like image 41
Scott Stanchfield Avatar answered Sep 25 '22 19:09

Scott Stanchfield