Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!fu-berlin.de!uni-berlin.de!not-for-mail From: ram@zedat.fu-berlin.de (Stefan Ram) Newsgroups: comp.lang.java.programmer Subject: Re: unnecessary code in Oracle example? Date: 9 Oct 2013 19:04:04 GMT Organization: Stefan Ram Lines: 51 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de yR/Era3aZXnbWMRvUt0thgNe3uiRGsfOCcWzXqfeBoP/6L X-Copyright: (C) Copyright 2013 Stefan Ram. All rights reserved. Distribution through any means other than regular usenet channels is forbidden. It is forbidden to publish this article in the world wide web. It is forbidden to change URIs of this article into links. It is forbidden to remove this notice or to transfer the body without this notice. X-No-Html: yes Content-Language: en Xref: csiph.com comp.lang.java.programmer:26256 Daniel Pitts 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.