Re: small java exercise
On May 16, 4:28 pm, Patricia Shanahan <p...@acm.org> wrote:
Martin Gregorie wrote:
Patricia Shanahan wrote:
...
try-finally does not require any use of exceptions. It just provides a
way of having the finally block run on completion of the try block.
I thought single exit was a very good idea when I was programming in
assembly languages and later in C. Is it a good idea in Java, or just a
habit?
Patricia
For me, habit. I worked a long time on a C app with setjmp/longjmp put
in TRY/CATCH/FINALLY macro constructs. If a developer did a return
inside of the macros, the return stack was corrupted. I hate
convoluted if/else logic worse, though, so I am not completely against
multiple exit points. But something like this would not be good IMHO,
even though it works as I would expect:
public class EarlyExit {
private final int ageForPG = 13;
private final int ageForR = 18;
public boolean oldEnough(int age) {
try {
if (age > ageForR) {
System.out.println("Old enough");
return true;
}
}
finally {
if (age < ageForPG) {
System.out.println("Go away, kid, ya bother me!");
return false;
}
}
System.out.println("How old are you again?");
return false;
}
public static void main(String[] args) {
EarlyExit test = new EarlyExit();
test.oldEnough(16);
test.oldEnough(21);
test.oldEnough(10);
}
}
How old are you again?
Old enough
Go away, kid, ya bother me!
Tim