2/08/2008

Null-Initialization in Java

In many languages (C++), uninitialized variables lead to errors. So, it's considered to be a good style to initialize every variable with 0 or null.

however, in Java it's quite the opposite.
Initialization with null is not recommended for those class members that should not be null.

Instead, it's recommended to declare those members final and initialize only once with an adequate value.


See example below.


Bad practice:

private CCollectorTarget m_collectTrg = null;

private CCollectorSchema m_collectSchm = null;

private CCollectorProject m_collectPrj = null;

private CCollectorFiles m_collectFiles = null;

public CCollectorData( CCollectorTarget collectTrg,
CCollectorSchema collectSchm,

CCollectorProject collectPrj,

CCollectorFiles collectFiles )

{

m_collectSchm = collectSchm;
m_collectTrg = collectTrg;
m_collectPrj = collectPrj;
m_collectFiles = collectFiles;
}

Good practice:

private final CCollectorTarget m_collectTrg;
private final CCollectorSchema m_collectSchm;
private final CCollectorProject m_collectPrj;
private final CCollectorFiles m_collectFiles;

public CCollectorData( CCollectorTarget collectTrg,
CCollectorSchema collectSchm,

CCollectorProject collectPrj,

CCollectorFiles collectFiles )

{

m_collectSchm = collectSchm;
m_collectTrg = collectTrg;
m_collectPrj = collectPrj;
m_collectFiles = collectFiles;
}

This technique has additional advantages: java compiler detects cases when you

  1. forget to initialize variable, or
  2. try to initialize it more than once.

Комментариев нет: