Re: general performance question
- From: Lew <lew@xxxxxxxxxxxxx>
- Date: Wed, 30 Jan 2008 21:02:55 -0500
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
.
- References:
- general performance question
- From: Tobi
- Re: general performance question
- From: Matt Humphrey
- Re: general performance question
- From: grasp06110
- general performance question
- Prev by Date: Re: package com.ibm.security.x509 does not exist
- Next by Date: Re: XML support in Java 5?
- Previous by thread: Re: general performance question
- Next by thread: Re: general performance question
- Index(es):
Relevant Pages
|