Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Jim Janney Newsgroups: comp.lang.java.programmer Subject: Re: unnecessary code in Oracle example? Date: Wed, 09 Oct 2013 20:56:38 -0600 Organization: bilaterally symmetric Lines: 47 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx05.eternal-september.org; posting-host="c75a2e3068ccf6c98395286f3e40b97d"; logging-data="23845"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+0kPn8rYR5odbqTsdOxmJi" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.3 (gnu/linux) Cancel-Lock: sha1:0oODPPDXOEvvANPcRb6Bo8JvmG0= sha1:tHo4xvpsV/xbrTy2l0UpSv8gdno= Xref: csiph.com comp.lang.java.programmer:26269 markspace writes: > On 10/9/2013 1:21 PM, Jim Janney wrote: >> Yes, in Java 7 you can have clean syntax and clean semantics. Looks >> like a win all around. >> > > For Java 5+, with varargs you could do (not compiled): > > public class MyIoUtils { > > public static void closeAll( Closeable ... toClose ) { > for( Closeable closeMe : toClose ) > try { > if( closeMe != null ) closeMe.close(); > } catch( IOException ex ) { > Logger.getLogger( "MyIoUtils" ).log( ex ); > } > } > } > > and get a somewhat cleaned up try catch > > OutPutStream io1 = null; > BufferedStream bs = null; > try { > io1 = new OutputStream( ... > bs = new BufferedStream( io1, ... > // do stuff > } > finally { > MyIoUtils.closeAll( bs, io1 ); > } > > Mostly I don't care for deep nesting, I think it reads poorly, and I > think it can also be hard to trace out for a programmer reading the > source. Giving the concept of closing a lot of objects a name like > "closeAll" promotes literate programming, imo. Mmm... you're complicating the code with extra assignments and tests, just to avoid one layer of nesting. I like the version with two try-finally blocks, partly because the lexical structure reflects what's happening in the code: two independent cleanups. But the Java 7 version is better. -- Jim Janney