Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6469271
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T05:58:18+00:00 2026-05-25T05:58:18+00:00

I would like some advice on a technique I bumped onto. It can be

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T05:58:18+00:00Added an answer on May 25, 2026 at 5:58 am

    It is nice.

    No major complaints, minor things off the top of my head:

    • a little performance burden
    • you need to make some things final for the Compensation to see them. Maybe this prevents some use-cases
    • you should catch exceptions during compensate and continue running Compensations no matter what
    • (bit far-fetched) you could accidentally empty out the Compensation queue at run-time due to a programming error. OTOH programming errors can happen anyway. And with your Compensation queue, you get “conditional finally blocks”.
    • don’t push this too far. Within a single method it seems okay (but then you probably don’t need too many try/finally blocks anyway), but don’t pass Compensation queues up and down the call stack.
    • it delays compensation to the “outermost finally” which could be a problem for things that need to be cleaned up early
    • it only makes sense when you need the try block only for the finally block. If you have a catch block anyway, you might just add the finally right there.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm looking into building a distributed application and would like some advice on the
I would like some advice about the following Makefile. It works fine, but it
I would like some advice on the best approach to use in the following
I am designing RESTful Api's and would like some advice on designing an API
I am considering starting an OSS project and would like some advice. I would
I would like some advice on how to best layout my JPA entity classes.
I would like some advice from anyone experienced with implementing something like pessimistic locking
I'm starting a new project and would like some advice. The purpose is to
I am new to the MVVM model, so I would like some advice, the
I'm not much of a database guru so I would like some advice. Background

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.