I may not be 100% correct in this (who ever is?) but I believe the best practice in a case like this is to:
1. Declare all variables at the top of the scope in which they are to be used.
For instance, a class level variable would be declared as follows:
Code:
public class Connector{
private Connection aConnection;
//..other variables and methods
A method variable would be as follows:
Code:
private void doSomething(){
Connection con;
//..do stuff..
}
2. Only initialize variables that are intended to have a default value, otherwise intialize them as needed.
In this and most cases, null is rarely an acceptable or intended value. I never initialize to null unless I have to.
Am example of what I mean:
Code:
public class Connector{
private Connection aConnection;
public void doSomething(){
try{
aConnection = getConnection();
}
catch(SQLException ex){
ex.printStackTrace();
aConnection = null;//Now i think i need null
}
if(null == aConnection){
//Error logic
}
}
private void getConection() throws SQLException{
//Connection code here
}
}
With a little more thought and ingenuity I bet I could find a way to eliminate null from the picture, with perhaps an Object of type InvalidConnection that implements Connection and throws meaningful errors when you try to use it's methods.
Maybe a little off topic, but those are some of my thoughts...
Comments?
Rich