Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.java.programmer Subject: Re: A little help with some logic Date: Sat, 6 Aug 2016 11:13:59 +0200 Lines: 88 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net STqZKEmNYM034+mPFnFelAg8JGMfFCUReizGzWtZnJ06+Laqo= Cancel-Lock: sha1:NdTCCuCPoSVdrW7U+NmusFPlNjY= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.2.0 In-Reply-To: Xref: csiph.com comp.lang.java.programmer:35221 On 05.08.2016 01:44, Knute Johnson wrote: > On 8/4/2016 06:28, Eric Sosman wrote: >> (This checks in the first order you mention, so I guess the >> second order was an "it is too late" slip-up.) >> >> It seems clear enough to me. All I'd suggest is that an >> exists() test might be a good idea in the File case, and that >> something more severe than printStackTrace() is probably called >> for if URISyntaxException gets thrown. >> >> One other item that might or might not interest you: I've seen >> that File's toURI() sometimes omits the "authority" part, giving >> the unusable "file:/C:/foo.dat" instead of "file:///C:/foo.dat". >> When I first ran into this I got around it with some heavy-handed >> string-bashing, but (says the JavaDoc) the java.nio.Path{,s} classes >> may offer a better way. Haven't tried them myself (for this purpose). >> > > Thanks Eric and Stefan for looking at it. Here's what I ended up with > > try { > URI uri = null; > URL url = getClass().getResource(source); > if (url != null) > uri = url.toURI(); > if (uri == null) { > File file = new File(source); > if (file.exists()) > uri = file.toURI(); > } > if (uri == null) > uri = new URL(source).toURI(); > > // use the URI > } catch (URISyntaxException|MalformedURLException ex) { > // deal with the exceptions > } I would still do it differently: the main change I'd do is to separate obtaining the URI from using it. This gives much clearer code because you can get rid of all the null checks and replace it with one: private URI parseURI(final String s) { final URL url = getClass().getResource(s); if (url != null) try { return url.toURI(); } catch (URISyntaxException e1) { // continue with next } final File f = new File(s); if (f.exists()) return f.toURI(); try { return new URL(s).toURI(); } catch (MalformedURLException e) { return null; } catch (URISyntaxException e) { return null; } } public void doSomethingWith(final String source) { final URI uri = parseURI(source); if (uri == null) { // too bad, did not work } else { // OK, let's do it } } Note, we could nest the checks with File and later in the first catch block but IMO that would obfuscate what the code does (i.e. try one method after the other). Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/