Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Best practice question

Status
Not open for further replies.

sreenath205

Programmer
Dec 9, 2003
17
IN

Hi All,

I know the title of the post does not make much sense, I am sorry for that.

The question i have is consider this piece of code

Code:
Connection mConnection = null;

mConnection = getConnection(); //This is a private method whic returns a connection object

Now consider this

Connection mConnection = getConnection();

Which is the best approach and if possible please give a small explanation/pointers/links why it is the best??

Thanks
Sreenath M
 
both approaches i believe are ok, however the approach used depends on the scope of connection object.
The first approach means u can use the connection object outside the scope of the getConnection() method, wheras the second limits the use to the scope of Connection con=getConnection()
 
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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top