Initialisation and Definite Assignment

11 PM October 14, 2003

A neat feature of Java is that it checks local variables are definitely assigned before they are first used. Because of this, it is not always necessary to initialise local variables in their declaration.

For instance, take this Java code snippet, which declares and initialises a variable named forward:


ActionForward forward = new ActionForward();
if (i > 5) {
calculateSummaryData();
forward = mapping.findForward(“big”);
} else {
calculateDetailedData();
forward = mapping.findForward(“small”);
}
return forward;

The initialisation of the forward variable in the first line is redundant; the assigned ActionForward object will never be used. The snippet could be rewritten as:


ActionForward forward; // no initialisation
if (i > 5) {
calculateSummaryData();
forward = mapping.findForward(“big”);
} else {
calculateDetailedData();
forward = mapping.findForward(“small”);
}
return forward;

This second form has several advantages:

  1. It does not create a dummy ActionForward instance that will be discarded.
  2. It protects against some kinds of coding errors. If a change to the code results in the code>forward variable not being definitely assigned, the compiler will flag an error. The compiler could not flag an error if the variable were initialised with a dummy value.
  3. It more correctly captures the intention of the code.

When I first started coding Java (in 1997) all Java programmers seemed to know and use definite assignment. Over the past few years, however, I have seen more and more code that initialises variables unnecessarily. I wonder why this is. Any suggestions?

By alang | # | Comments (4)
(Posted to javablogs, Software Development and Java)

Windows NT4.0

11 PM October 14, 2003

I’m using Win NT 4.0 at work at the moment on a fairly modern PC. It stinks:

  • Microsoft won’t support it with a decent version of Windows Media Player, or any new software for that matter.
  • Regularly goes into a trance when switching applications. Hard disk drive light goes flat out, CPU usage drops to zero and the mouse pointer freezes. Suspect it’s because NT can’t cope with 1Gb of memory.
  • It can barely multi-task. Has trouble compiling Java and playing music at the same time. Mouse pointer gets jerky as CPU load rises above 80%.

Remember this next time someone tries to tell you that Windows XP is no better than NT 4.0.

By alang | # | Comments (1)
(Posted to Software Development)
© 2003-2006 Alan Green