I am writing a routine which has the following form:
TRY A
IF no success, B
IF no success, RETRY A
IF no success, throw error
It's not trivial to extract either A or B into it's own routine, so what is most simple structure that will allow me to retry A without code duplication?
Currently, I have a do..while that allows N retries:
int retries = 1;
do {
// DO A
if ( /*success*/ ) {
break;
} else if (retries > 0) {
// DO B
if ( /*success*/) {
break;
}
} else {
// throw Error
}
} while (retries-- > 0);
This is ugly and not ideal as it implies that I might want to ever retry more than once, which I don't. I will have to use a loop, but there has to be a more simple way that I'm not seeing.
For context, this is code generated in Java, executing SQL statements to try an UPDATE first, then if no entry to update is found, INSERT, and if that command fails (concurrency, already created), try UPDATE again.

DoA()andDoB()could not be their own methods. If the two methods depend on each other, then have an interface which forces implementations ofDoA()andDoB(). Then, you can have a small class that implements both. The two methods can share the state with each other with properly synchronized members. I think that logic should be separate-able. Now, are you generating logic like this for various types of tables or is this limited to a finite number of cases? Or two methods can remain functional and communicate entirely through input parameters – Job Dec 7 '11 at 2:58tryblocks. – NickC Dec 7 '11 at 5:08