The dual-band if
Sometimes, one wants to write code like this pseudocode:
if( final Result result = calculate() )use( result );
This assumes that ?result = calculate()? assigns the result of
the calculation to ?result?, but also that the attempt to
calculate might fail and that the following statement ?use(
resource );? only is executed if the attempt has not failed.
In Java, something like this is possible with exceptions, but
control flow with exceptions is more difficult than structured
control (e.g., when nesting two such attempts) and the code
would still look more complicated than the code above.
One might like to encapsulate the exception handling into a
method or class, but this does not solve the question how to
return two results: A flag to indicate success or failure
/and/ an actual result.
Now I have found a means to actually do this in Java, which
looks very similar to the pseudocode above and is not much
longer. I call it the ?dual-band if? because it uses two
?bands? to pass information: One for the success-flag and
another one for the actual value, which therefore can take all
possible values of its type (including ?null?).
This technique also allows to encapsulate the redundancy one
encounters in the if-instanceof-then-downcast idiom
if( object instanceof Example )
{ final Example example =( Example )object; ... }
It can be written more concise, like the pseudocode:
if( final Example example=( Example )object )...
And this technique even allows something as in the RAII
idiom (of C++), where a resource is automatically released at
the end of a block without an explicit request to do so.
(However, in Java this is of limited use for java.io.Closable
objects, because the close operation might fail, and such
failure often needs to be handled by the application, so it
can not be encapsulated into an library object.)
Possibly, readers might like to try to find such a pattern
themselves. Otherwise, they can read about it on the web page
with the following URI (I wrote this down onto a web page,
because it might be deemed too long for a Usenet post):
http://www.purl.org/stefan_ram/pub/dual-band_if