What is the "Execute Around" idiom?

What is this "Execute Around" idiom (or similar) I've been hearing about? Why might I use it, and why might I not want to use it?

Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource". For example:

public interface InputStreamAction
{
    void useStream(InputStream stream) throws IOException;
}

// Somewhere else    

public void executeWithFile(String filename, InputStreamAction action)
    throws IOException
{
    InputStream stream = new FileInputStream(filename);
    try {
        action.useStream(stream);
    } finally {
        stream.close();
    }
}

// Calling it
executeWithFile("filename.txt", new InputStreamAction()
{
    public void useStream(InputStream stream) throws IOException
    {
        // Code to use the stream goes here
    }
});

// Calling it with Java 8 Lambda Expression:
executeWithFile("filename.txt", s -> System.out.println(s.read()));

// Or with Java 8 Method reference:
executeWithFile("filename.txt", ClassName::methodName);

The calling code doesn't need to worry about the open/clean-up side - it will be taken care of by executeWithFile.

This was frankly painful in Java because closures were so wordy, starting with Java 8 lambda expressions can be implemented like in many other languages (e.g. C# lambda expressions, or Groovy), and this special case is handled since Java 7 with try-with-resources and AutoClosable streams.

Although "allocate and clean-up" is the typical example given, there are plenty of other possible examples - transaction handling, logging, executing some code with more privileges etc. It's basically a bit like the template method pattern but without inheritance.

What is a pronoun? (video), A noun is a word that describes a person, place, thing, or idea. less than a clause (or a Duration: 4:28 Posted: Jan 27, 2016 Some exceptions When the noun refers to someone or something that is unique or is thought of as unique or exists as only one at a time: the Lord, the Messiah, the devil, the sun, the earth, the universe, the Pope, the Dalai Lama

The Execute Around idiom is used when you find yourself having to do something like this:

//... chunk of init/preparation code ...
task A
//... chunk of cleanup/finishing code ...

//... chunk of identical init/preparation code ...
task B
//... chunk of identical cleanup/finishing code ...

//... chunk of identical init/preparation code ...
task C
//... chunk of identical cleanup/finishing code ...

//... and so on.

In order to avoid repeating all of this redundant code that is always executed "around" your actual tasks, you would create a class that takes care of it automatically:

//pseudo-code:
class DoTask()
{
    do(task T)
    {
        // .. chunk of prep code
        // execute task T
        // .. chunk of cleanup code
    }
};

DoTask.do(task A)
DoTask.do(task B)
DoTask.do(task C)

This idiom moves all of the complicated redundant code into one place, and leaves your main program much more readable (and maintainable!)

Take a look at this post for a C# example, and this article for a C++ example.

Introduction to nouns (video), There are two main ways to pronounce this little word, based largely on what word follows it. If the is followed by a word which begins with a consonant sound ( � New York Times Notable Book New York Times Bestseller What Is the What is the epic novel based on the life of Valentino Achak Deng who, along with thousands of other children —the so-called Lost Boys—was forced to leave his village in Sudan at the age of seven and trek hundreds of miles by foot, pursued by militias, government bombers, and wild animals, crossing the deserts of three

An Execute Around Method is where you pass arbitrary code to a method, which may perform setup and/or teardown code and execute your code in between.

Java isn't the language I'd choose to do this in. It's more stylish to pass a closure (or lambda expression) as the argument. Though objects are arguably equivalent to closures.

It seems to me that the Execute Around Method is sort of like Inversion of Control (Dependency Injection) that you can vary ad hoc, every time you call the method.

But it could also be interpreted as an example of Control Coupling (telling a method what to do by its argument, literally in this case).

The, A mammogram is an X-ray picture of the breast. Doctors use a mammogram to look for early signs of breast cancer. Regular mammograms are the best tests� Is definition is - present tense third-person singular of be; dialectal present tense first-person and third-person singular of be; dialectal present tense plural of be How to use is in a sentence.

I see you have a Java tag here so I'll use Java as an example even though the pattern isn't platform-specific.

The idea is that sometimes you have code that always involves the same boilerplate before you run the code and after you run the code. A good example is JDBC. You always grab a connection and create a statement (or prepared statement) before running the actual query and processing the result set, and then you always do the same boilerplate cleanup at the end--closing the statement and connection.

The idea with execute-around is that it's better if you can factor out the boilerplate code. That saves you some typing, but the reason is deeper. It's the don't-repeat-yourself (DRY) principle here--you isolate the code to one location so if there's a bug or you need to change it, or you just want to understand it, it's all in one place.

The thing that's a little tricky with this kind of factoring-out though is that you have references that both the "before" and "after" parts need to see. In the JDBC example this would include the Connection and (Prepared)Statement. So to handle that you essentially "wrap" your target code with the boilerplate code.

You may be familiar with some common cases in Java. One is servlet filters. Another is AOP around advice. A third is the various xxxTemplate classes in Spring. In each case you have some wrapper object into which your "interesting" code (say the JDBC query and result set processing) is injected. The wrapper object does the "before" part, invokes the interesting code and then does the "after" part.

What Is a Mammogram?, What is the difference between Influenza (Flu) and COVID-19? Influenza (Flu) and COVID-19 are both contagious respiratory illnesses, but they� Question: "What is the gospel?" Answer: The word gospel literally means “good news” and occurs 93 times in the Bible, exclusively in the New Testament. In Greek, it is the word euaggelion, from which we get our English words evangelist, evangel, and evangelical.

See also Code Sandwiches, which surveys this construct across many programming languages and offers some interesting research’y ideas. Concerning the specific question of why one might use it, the above paper offers some concrete examples:

Such situations arise whenever a program manipulates shared resources. APIs for locks, sockets, files, or database connections may require a program to explicitly close or release a resource that it previously acquired. In a language without garbage collection, the programmer is responsible for allocating memory before its use and releasing it after its use. In general, a variety of programming tasks call for a program to make a change, operate in the context of that change, and then undo the change. We call such situations code sandwiches.

And later:

Code sandwiches appear in many programming situations. Several common examples relate to the acquisition and release of scarce resources, such as locks, file descriptors, or socket connections. In more general cases, any temporary change of program state may require a code sandwich. For example, a GUI-based program may temporarily ignore user inputs, or an OS kernel may temporarily disable hardware interrupts. Failure to restore earlier state in these cases will cause serious bugs.

The paper does not explore why not to use this idiom, but it does describe why the idiom is easy to get wrong without language-level help:

Defective code sandwiches arise most frequently in the presence of exceptions and their associated invisible control flow. Indeed, special language features to manage code sandwiches arise chiefly in languages that support exceptions.

However, exceptions are not the only cause of defective code sandwiches. Whenever changes are made to body code, new control paths may arise that bypass the after code. In the simplest case, a maintainer need only add a return statement to a sandwich’s body to introduce a new defect, which may lead to silent errors. When the body code is large and before and after are widely separated, such mistakes can be hard to detect visually.

Symptoms of Coronavirus, Ammonium nitrate: what is the chemical blamed for blast in Lebanese capital? The deadly explosion in Beirut has been blamed on thousands of� Are, basic unit of area in the metric system, equal to 100 square metres and the equivalent of 0.0247 acre. Its multiple, the hectare (equal to 100 ares), is the principal unit of land measurement for most of the

Ammonium nitrate: what is the chemical blamed for blast in , There is also a federal deadline each academic year. Select your state of legal residence and the school year for which you're applying for federal student aid. Subscribe to Continue Reading. You’ve run out of free articles. Join Slate Plus to continue reading, and you’ll get unlimited access to all our work—and support Slate’s independent journalism.

Apply for Financial Aid, Explore iPhone, the world's most powerful personal device. Check out Which iPhone is right for you? Compare all Why Apple is the best place to buy. Where definition is - at, in, or to what place. How to use where in a sentence.

iPhone, The virus in question was a coronavirus that caused an epidemic of severe acute Duration: 5:16 Posted: May 14, 2020 The .com at the end of many web addresses (such as Lifewire.com) is called a top-level domain (TLD). The .com ending is the most common generic top-level domain. The .com TLD represents a commercial domain, which conveys the type of content that's published.

Comments
  • I hadn't noticed it was you, tack. Otherwise I might have been more sarcastic in my answer ;)
  • So this is basically an aspect right? If not, how does it differ?
  • It's deterministic. Finalizers in Java aren't called deterministically. Also as I say in the last paragraph, it's not only used for resource allocation and cleanup. It may not need to create a new object at all. It's generally "initialization and tear-down" but that may not be resource allocation.
  • So it's like in C where you have a function that you pass in a function pointer to do some work?
  • Also, Jon, you refer to closures in Java - which it still doesn't have (unless I missed it). What you describe are anonymous inner classes - which are not quite the same thing. True closures support (as have been proposed - see my blog) would simplify that syntax considerably.
  • @Phil: I think it's a matter of degree. Java anonymous inner classes have access to their surrounding environment in a limited sense - so while they're not "full" closures they're "limited" closures I would say. I would certainly like to see proper closures in Java, although checked (continued)
  • Java 7 added try-with-resource, and Java 8 added lambdas. I know this is an old question/answer but I wanted to point this out for anyone looking at this question five and a half years later. Both of these language tools will help solve the problem this pattern was invented to fix.
  • Good point, azurefrag. I have revised and expanded my answer so that it really is more of a self-contained answer in its own right. Thanks for suggesting this.
  • + for the imagination :D
  • If my open fails (say acquiring a reentrant lock) the close is called (say releasing a reentrant lock despite the matching open failing).