Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

advice on nested Java try/finally code sandwiches

Tags:

I would like some advice on a technique I bumped onto. It can be easily understood by looking at the code snippets, but I document it somewhat more in the following paragraphs.


Using the "Code Sandwich" idiom is commonplace to deal with resource management. Used to C++'s RAII idiom, I switched to Java and found my exception-safe resource management resulting in deeply nested code, in which I have a really hard time getting grip on the regular control flow.

Apparently (java data access: is this good style of java data access code, or is it too much try finally?, Java io ugly try-finally block and many more) I'm not alone.

I tried different solutions to cope with this:

  1. maintain the program state explicitly: resource1aquired, fileopened..., and cleanup conditionally: if (resource1acquired) resource1.cleanup()... But I shun duplicating the program state in explicit variables - the runtime knows the state, and I don't want to care for it.

  2. wrap every nested block in functions - results in even harder to follow control flow, and makes for really awkward function names: runResource1Acquired( r1 ), runFileOpened( r1, file ), ...

And finally I arrived at an idiom also (conceptually) backed by some research paper on code sandwiches:


Instead of this:

// (pseudocode) try {    connection = DBusConnection.SessionBus(); // may throw, needs cleanup    try {         exported = false;         connection.export("/MyObject", myObject ); // may throw, needs cleanup         exported = true;             //... more try{}finally{} nested blocks     } finally {         if( exported ) connection.unExport( "/MyObject" );     }    } finally {    if (connection != null ) connection.disconnect(); } 

Using a helper construction, you may arrive at a more linear construct, in which compensation code is right next to the originator.

class Compensation {      public void compensate(){}; } compensations = new Stack<Compensation>(); 

And the nested code becomes linear:

try {     connection = DBusConnection.SessionBus(); // may throw, needs cleanup     compensations.push( new Compensation(){ public void compensate() {         connection.disconnect();     });      connection.export("/MyObject", myObject ); // may throw, needs cleanup     compensations.push( new Compensation(){ public void compensate() {         connection.unExport( "/MyObject" );     });         // unfolded try{}finally{} code  } finally {     while( !compensations.empty() )         compensations.pop().compensate(); } 

I was delighted: no matter how many exceptional paths, the control flow stays linear, and the cleanup code is visually next to the originating code. On top of that, it doesn't need an artificially restricted closeQuietly method, which makes it more flexible (i.e. not only Closeable objects, but also Disconnectable, Rollbackable and whatever others).

But...

I found no mention of this technique elsewhere. So here's the question:


Is this technique valid? What bugs do you see in it?

Thanks a lot.

like image 250
xtofl Avatar asked Aug 31 '11 09:08

xtofl


2 Answers

I like the approach, but see a couple of limitations.

The first is that in the original, a throw in an early finally block doesn't affect later blocks. In your demonstration, a throw in the unexport action will stop the disconnect compensation happening.

The second is that it the language is complicated by the ugliness of Java's anonymous classes, including the need to introduce a heap of 'final' variables so they can be seen by the compensators. This is not your fault, but I wonder if the cure is worse than the disease.

But overall, I like the approach, and it is quite cute.

like image 101
Burleigh Bear Avatar answered Oct 21 '22 15:10

Burleigh Bear


The way I see it, what you want are transactions. You compensations are transactions, implemented a bit differently. I assume that you are not working with JPA resources or any other resources that support transactions and rollbacks, because then it would be rather easy to simply use JTA (Java Transaction API). Also, I assume that your resources are not developed by you, because again, you could just have them implement the correct interfaces from JTA and use transactions with them.

So, I like your approach, but what I would do is hide the complexity of popping and compensating from the client. Also, you can pass transactions around transparently then.

Thus (watch out, ugly code ahead):

public class Transaction {    private Stack<Compensation> compensations = new Stack<Compensation>();     public Transaction addCompensation(Compensation compensation) {       this.compensations.add(compensation);    }     public void rollback() {       while(!compensations.empty())          compensations.pop().compensate();    } } 
like image 31
LeChe Avatar answered Oct 21 '22 14:10

LeChe