Alright here's a little Java puzzler - not on the order of Josh Bloch but still I'm surprised how such a simple problem can give me such a headache . . . . .
I know several ways to solve it (probably those that are the most obvious ones) but I'm hoping others can see a more elegant / less hacky solution.
(Perhaps there's a really embarrassingly obvious answer but after several interrupted nights of sleep due to our newborn I'm just not seeing it)
The issue at hand is we want to perform a business operation and keep track (in memory) of the job's state. It's not critical that the job succeed but it is ABSOLUTELY critical that we record the state of the Job correctly.
So first off here is some pseudocode:
Set Job Status to "New"
If job fails set status to "Failed"
If job succeeds set status to "Success"
Simple right? Well the problem comes in when you have exception handling so here's a quick first cut of the code that I wrote
Clearly I'd want to store / log why things failed but let's not worry about that for the moment.
Anyway so that's pretty simple, and looks correct, but wait - what if an unchecked exception is thrown. I really don't want to catch RuntimeException (let's not even thing about catching an Error / Throwable) .
So perhaps I add a finally block - so that if the status is still "NEW" then clearly an exception was thrown that was not the Checked exception.
So here's Version #2
But that looks so hacky and also someone reading the code is really going to have to think about it to see if all paths are appropriate (as compared to the pseudocode which is "obviously" right).
True I could mimic the pseudocode outlined above and catch any exceptions in the launchJob() method (including RuntimeException?) to get code as follows:
but perhaps as the caller of launchJob() I am not aware of the catching of all those Exceptions (including Runtime?) in the method (say it's some vendor / 3rd party / external API) and so I go back to wrapping again but this time without the catch block
A little cleaner but still - the pseudocode is the cleanest of all - why can't I map it to Java more easily and not worry about possible Exceptions and the resulting ugly code?
(p.s. this problem highlights for me one of the key issues developers must face that isn't talked about much - not just solving the abstract problem - for me the solution to that is the pseudocode - but here the hard issue is mapping the solution to a language and understanding the behavior of that language - exception handling, how unchecked exception work etc.)