KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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: 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. 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( "
Tags (comma-separated)
Save Edits
Cancel