Re: small java exercise
Patricia Shanahan <pats@acm.org> writes:
In this case, I am not so much giving advice as asking for
insight. Are there advantages in Java to pushing for single
exit that outweigh the cost of making the code more
complicated, for example by requiring a "retVal"? If so, what
are they?
The usual benefits of ?structured programming?.
- With a single exit at the end, if I would want to add a
call to be done once before the method exits, I would add
it in front of this exit point. Otherwise, one would need
to find all exit points and add this call in front of
each one.
- A kind of ?referential transparency? of blocks. By this
(ignoring parameters and return values for simplicity),
a methode declaration
m(){ ... { ... } ... }
can always be refactored to
m1(){ ... } // = the ?{ ... }? block from above
m(){ ... m1(); ... }
Thus, a block can always be replaced by a call to this
block after it has been given a name by a method
declaration.
This is not possible anymore, when this block contains
an exit (?return?).
- Improved readability. In
{ ...
{ ... }
f();
... }
I know that ?f();? will be executed whenever the whole
block is executed if the block is written according to
structured programming rules. I do not have to analyze the
inner block to make this assertion. When jump-statements,
like ?return;? are allowed, one can not make such
assertions with the same ease.
Once I have read that in certain C++ implementations multiple
returns can speed up a function, which would be slowed down by
an enforcement of the single-exit rule. This would be one of
the cases, where I would refrain from enforcing a single exit:
If code needs to be optimized for runtime speed. In general,
I like and apply the single-exit rule.