The dual-band if

S

Stefan Ram

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
 
R

Robert Klemme

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.

This pattern is only useful for loops not for simple if statements. For
those it's much cleaner to write

final Result result = calculate()
if ( result ) ...

I do not see any benefit in squeezing the assignment into the condition.
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

Frankly, I find your solution rather hackish. Especially the fact that
you use keyword "for" for something that is not an iteration makes code
harder to read. Also, your iterator has issues of its own - let alone
the fact that it is generally a bad idea to have a class implement
Iterable and Iterator at the same time.

If you need to do calculations that can fail and whose failure is non
exceptional (btw, do you have concrete examples for this situation?)
there are other ways you can do it. For example:

1. use /null/ as return value for non successful calculations.

2. use a class encapsulating the result plus a flag.

3. use the command pattern and store an additional flag in the command
object that tells you the outcome of the calculation

Regards

robert
 
L

Lew

Stefan said:

You use a custom class "Type" in one of the examples, which might be slightly
confusing to those accustomed to thinking of java.lang.reflect.Type.

Since Class implements Type, that's not as rare as you might think.

It's a truly interesting technique, using "for()" to simulate the "dual-band
if". I think some of the idioms are more obscure than the more naive and
verbose way to which we are accustomed, but properly designed they do help
prevent accidental resource leaks, a Good Thing.

Thanks for this groovy hack.
 
E

Ed Kirwan

Stefan said:
Sometimes, one wants to write code like this pseudocode:
snip
http://www.purl.org/stefan_ram/pub/dual-band_if

Stefan, I think I remember reading some time ago that you always fully
qualify your types in Java, and someone else mentioned that this made your
code a little more ... how should I put this? ... strenuous to read; and I
think you wrote back to say that this is just the way you write code and
that's really all there is to it.

(I can't find the thread, so I may be entirely mistaken: if so, apologies.)

I applaud your experimenting with this dual-band if: it's interesting.

I don't fully understand it as I've not read through your paper yet: and I
just wanted to say that one of the reasons that I haven't read through your
paper is that I find all the, "finals," and fully-qualified types a little
off-putting.

I don't for one moment presume to tell you how to write your code: you are
of course master of your domain. I just wanted to give you a little
feedback from your audience because, as I mentioned, I find your work
interesting.
 
S

Stefan Ram

Mark Space said:
403 Access Denied. ?

Thanks for the notice! I am sorry for this denial.

Some clients might get this inadvertently as a side
effect of rules put in place to cope with annoying
request.

Your request, of course, is not considered to be an
annoyance. I don't know why this denial happened.

To allow a simple and instantaneous access method for you,
I have created a temporary copy with less restrictive rules:

http://userpage.fu-berlin.de/~ram/pub/all/tmp.html

This URI, however, might be associated with
a resource during the next 3 days only.
 
S

Stefan Ram

Ed Kirwan said:
and fully-qualified types a little off-putting.

I can understand this, because I am not so sure
myself about whether to keep on using this.

A problem I have with import statements is that
it is more difficult for me to copy and paste
snippets between a Java IDE and a general purpose
text editor or word processor, because I need to
remember to copy some import statements with it.

Some IDEs can do this for you, when you copy
between two source files kept in the IDE, but
this rarely applies to me.

I use an automatic reformatter (from the Eclipse)
project to reformat my classes to the usual
bracing style when publishing them as a part of
the publication of classes of the library ram.jar.

For example,

http://www.purl.org/stefan_ram/java/de/dclj/ram/notation/junobjects/Junobjects.java

This way, I can use my bracing style internally,
while the code published uses the common bracing
style.

The Eclipse formatter options look like this:

org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
....

If someone knows how to tell the Eclipse formatter
to replace full qualifications by import declarations,
I would happily include this there. This way, I can still
use full qualifications internally, while the code
published there will use import statements.

(Later, I intend to apply automatic reformatting to the
other web pages and, possibly, Usenet posts, too.)
 
L

Lew

Ed said:
all the ... "finals" ... a little off-putting.

The finals have a purpose, perhaps overprotectively so, to lock down the
values of certain variables. Shorter class names are helpful for pedagogical
discourse, and maybe example snippets can dispense with 'final' and other
things like complete exception handling, but conversely, emphasizing the value
of 'final' inline is helpful as a sidelong hint. Its very interruption of the
reader's cognitive process focuses one's attention on the idiom, and has one
think, "Hmm, that's right. Using 'final' is quite often a Good Thing."

'final' also makes values available to nested classes, not relevant to this
particular essay but nice to remember, and allows the JIT to really slick
things up.
 
B

bbound

Thanks for the notice! I am sorry for this denial.

Some clients might get this inadvertently as a side
effect of rules put in place to cope with annoying
request.

Rules put in place? We're talking retrieving and reading a file
passively here, not posting to a forum/guestbook/wiki/other spammable
resource. There's no reason for any access restrictions (given that
the contents of the "dual-band_if" file are not confidential).
Your request, of course, is not considered to be an
annoyance. I don't know why this denial happened.

It happened because you have overzealous security in place to cope
with ... I don't know what. Apparently not just blogspam or similarly.
To allow a simple and instantaneous access method for you,
I have created a temporary copy with less restrictive rules:

http://userpage.fu-berlin.de/~ram/pub/all/tmp.html

This URI, however, might be associated with
a resource during the next 3 days only.

Why not just make it permanent, or remove the "restrictive rules"? It
is a violation of Web norms (and possibly even the HTTP standard
itself) to randomly and gratuitously deny access to simple, non-form-
submitting GETs with 403s. Either it's non-public and should
consistently 403 (or, better yet, 404, so as not to reveal that
something exists there but is private), or it is public and should
consistently return the actual file.
 
M

Mark Space

Stefan said:
To allow a simple and instantaneous access method for you,
I have created a temporary copy with less restrictive rules:


Thanks for that. I haven't had a chance to digest everything in your
paper yet, but it looks quite interesting.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top