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:
ActionForward instance that will be discarded.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?
I’m using Win NT 4.0 at work at the moment on a fairly modern PC. It stinks:
Remember this next time someone tries to tell you that Windows XP is no better than NT 4.0.