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?
What is this Execute Around idiom (or similar) I’ve been hearing about? Why might
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
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.
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:
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-resourcesandAutoClosablestreams.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.