Re: general performance question
Matt Humphrey wrote (restoring the attribution that was elided):
Clearly there's no sense at any time in creating an object and then setting
it to null
grasp06110 wrote:
Sometimes I declare a variable that is to point to a resource and set
it to null so that the resource can be released in a wider scope. For
example:
Connection conn = null;
try {
conn = ConnectionFactory.getConnection();
doSomethingWithTheConnection(conn);
} finally {
if(conn != null) {
conn.close();
}
}
In other words, you have a sound engineering reason for where you place your
variable declaration - scope.
Declare the variable at the closest point within the appropriate scope to its
use. Do NOT initialize the variable to null unless null is a valid value for
it at the point of declaration, as in grasp's example. This is the best
practice as recommended by Joshua Bloch in /Effective Java/, for example.
I would work that particular example a little differently myself. I'm loathe
to assign to a variable twice when it only needs one value:
Connection conn; // declared with appropriate scope
try
{
conn = ConnectionFactory.getConnection();
if ( conn == null )
{
throw new SQLException( "No connection" );
}
}
catch ( SQLException exc )
{
logger.error( exc );
return;
}
assert conn != null; // invariant
try
{
doSomethingWithTheConnection(conn);
}
catch ( SQLException exc )
{
logger.error( exc );
}
finally
{
try
{
conn.close();
}
catch ( SQLException ex )
{
logger.error( ex );
}
}
--
Lew