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?
Comments
Well, unfortunately, if you are initializing variable in _try_ block the compiler may not understand it. I find it easier to assign it to null.
Somethimes the *compiler* isn't sure that a variable will definitely assigned, even though *you* are. Bloody thing. Perhaps this puts people into the habit of assigning to null.
Don't get this trouble with Python...
if (i > 5) { calculateSummaryData(); return mapping.findForward("big"); } else { calculateDetailedData(); return mapping.findForward("small"); } // not reachedOr:
String foundmapping; if (i > 5) { calculateSummaryData(); foundmapping = "big"; } else { calculateDetailedData(); foundmapping = "small"; } return mapping.findForward(foundmapping);both versions have less duplicated code.
See the the following link:
http://www.livejournal.com/users/notbrainsurgery/2237.html
Showing unecessary initialization enforced by JLS.