Re: unnecessary code in Oracle example?
Daniel Pitts <newsgroup.nospam@virtualinfinity.net> writes:
MyResource r1 = null;
MyResource r2 = null;
try {
r1 = openResource1();
r2 = openResource2();
} finally {
if (r1 != null) r1.close();
if (r2 != null) r2.close();
}
Which also might be written as follows
(execution would start at r() below,
code was never syntax-checked nor tested).
void use
( final MyResource r1,
final MyResource r2 )
{ /* insert the code that needs r1 und r2 here */ }
void r2
( final MyResource r1,
final MyResource r2 )
{ try
{ use( r1, r2 ); }
finally
{ r2.close(); }}
void r1( final MyResource r1 )
{ try
{ r2( r1, openRessource2() ); }
catch( final OpenResource2Exception exception )
{ /* add possible exception handling here */ }
finally
{ r1.close(); }}}
void r()
{ try
{ r1( openRessource1() ); }
catch( final OpenResource1Exception exception )
{ /* add possible exception handling here */ }}
The function calls are a trick that I have invented to
bypass the need for non-final null-initialized variables
when the reference of a resource just obtained is to be
stored in a variable.
I also do not have to compare the resources with null before
closing them, since the functions with the close() calls are
only called when the corresponding open calls did not throw.