5

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

 3 years ago
source link: https://www.codesd.com/item/should-i-keep-instance-variables-in-java-always-initialized-or-not.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

advertisements

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?


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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK