As part of writing an Iterator, I found myself writing the following piece of code (stripping error handling)
public T next() {
try {
return next;
} finally {
next = fetcher.fetchNext(next);
}
}
finding it slightly easier to read than
public T next() {
T tmp = next;
next = fetcher.fetchNext(next);
return tmp;
}
I know it's a simple example, where the difference in readability may not be that overwhelming, but I'm interested in the general opinion as to whether it is bad to use try-finally in cases like this where there are no exceptions involved, or if it is actually preferred when it simplifies the code.
If it's bad: why? Style, performance, pitfalls, ...?
Conclusion Thanks you all your answers! I guess the conclusion (at least for me) is that the first example might have been more readable if it was a common pattern, but that it isn't. Therefore the confusion introduced by using a construct outside of it's purpose, along with possibly obfuscated exception flow, will outweigh any simplifications.
finally
blocks.Iterator
, where you indeed need sort of prefetching in order forhasNext()
to work. Try it yourself.Iterator
is that you need to fetch the value inhasNext()
('cause fetching it is quite often the only way to find out if it exists) and return it innext()
just like the OP did.