Proposal: Automatic Resource Management
Joshua Bloch
jjb at google.com
Tue Mar 3 23:00:55 PST 2009
Neal,
> I'd expect it to be something like
>
> try {
> with (InputStream in : new FileInputStream(src))
> with (OutputStream out : new FileOutputStream(dest)) {
> byte[] buf = new byte[8 * 1024];
> int n;
> while ((n = in.read(buf)) >= 0)
> out.write(buf, 0, n);
> }
> } catch (IOException ex) {
> showDialog("Copy failed.");
> }
>
> Looks about as nice,
No it doesn't. Not even close. In java, the colon in this position would be
read by the typical programmer as "in" (e.g., "for each String s in
stringList"). What we want (and what my proposal provides) is the equals
sign (=), which means assignment. Also you have an extra level of nesting
for each variable. This is one of the things that we're trying to get away
from with this proposal. A more honest indentation for your syntax would
be:
try {
with (InputStream in : new FileInputStream(src)) {
with (OutputStream out : new FileOutputStream(dest)) {
byte[] buf = new byte[8 * 1024];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}
}
} catch (IOException ex) {
showDialog("Copy failed.");
}
That's three levels off indentation instead of one (more generallly, number
of resources + 1, instead of 1).
Josh
More information about the coin-dev
mailing list