amber-dev Digest, Vol 49, Issue 9

Brian Goetz brian.goetz at oracle.com
Thu Mar 25 13:54:09 UTC 2021



On 3/25/2021 8:58 AM, Vikram Bakshi wrote:
>> Any ideas how this could be made better? I though about try-catch
> expressions,
>> but it's still a lot of a code; I've thought about helper method like
>> getOrThrow(supplier, exception -> {}), but it's still feels like a half
>> solution
> There is a feature in the D programming language (and I believe in others)
> called 'scope guards'. I have never programmed in D before (Java is my
> bread and butter) but I came across it and definitely thought it would be
> useful in Java.

This is similar to (though stronger than) the `defer` mechanism in 
Golang.  It allows you to accumulate a sequence of actions to be 
potentially performed later.  The D feature is stronger because (a) it 
provides multiple accumulation sets and (b) works with arbitrary block 
boundaries (which is more refactoring-friendly) rather than function 
boundaries.

Saying `scope(failure) S` is similar to wrapping the remainder of the 
block with `try { remainder } catch (e) { S; throw e; }`.

Features like this have supporters and detractors.  The supporters point 
to the lower ceremony; the detractors point to the fact that it is 
harder to know what code will be executed if there is a failure at a 
given point.  Java tends to come down on the side of making things 
clearer through block structuring.




More information about the amber-dev mailing list