So I just came back from a 'meting' about a fix that we had to do which would fix an issue we had in production. Before the code goes out, it has to be presented to all these bunch of people. hate it!
Broken code (pseudo):
SomeClassA object1 = null
while loop
{
if (some condition){
// do something
}
else {
object1 = someOtherObject.getValueForObject1();
}
Record Date = object1.getRecordDate(); //this gets moved in fix
}
Suggested Code fix (pseudo)
SomeClassA object1 = null
while loop
{
if (some condition){
// do something
}
else {
object1 = someOtherObject.getValueForObject1();
Record Date = object1.getRecordDate();
}
}
Code fix after suggestions (pseudo):
while loop
{
if (some condition){
// do something
}
else {
SomeClassA object1 = null
object1 = someOtherObject.getValueForObject1();
Record Date = object1.getRecordDate();
}
}
Broken code gave a Null pointer exception because for a record the control never went into the else block...which in turn kept object1 as null.
I'm sure people out there have encountered this type of issue. what are your stories/or suggestions? is it always a good practice to declare variables when they are needed instead of on top (I think Effective Java says that).. Is it a bad practice to declare object as 'null'