Programming Search⌘K

Patterncore

Execute Around

Also called execute around method, execute-around method, execute around pattern.

An execute-around function does the setup, calls a block that its caller gives, and then always does the cleanup, so that callers cannot forget the cleanup.

Family
behavioral-design
Intent
When a pair of actions must be taken together, such as open and close, wrap the pair around a function that the caller passes in.
Also called
execute around method

Intent

When a pair of actions have to be taken together, such as file open and close, you can use a higher-order function that wraps the actions around the function that is passed in.1

Problem

Many resources need two actions: one before the work and one after it. A file must be opened and then closed. A lock must be taken and then released. A transaction must be started and then committed.

If each caller writes both actions, some caller will forget the second one, or an error will skip it. One comment on the WikiWikiWeb page says that you should not have to balance open() and close() calls throughout an application.1

Solution

Write one function that owns the pair of actions. The caller gives it the work as a block or a function. The function does the setup, calls the block, and then does the cleanup.1 The cleanup must also run when the block fails, so the function puts it in a finally or ensure clause.12

   caller                         execute-around function
     |  open_during(block)              |
     |--------------------------------->|  setup (open)
     |                                  |  try:
     |            block(resource)       |      call the block
     |<---------------------------------|
     |--------------------------------->|  finally:
     |                                  |      cleanup (close)
     |<-------- value of the block -----|

The WikiWikiWeb page shows the Smalltalk form. Instead of aFile open, the work, and aFile close, the caller writes aFile openDuring: [...], and the method openDuring: opens the file, evaluates the block and closes the file. The page refers to Smalltalk Best Practice Patterns for more.1

Example

The example files show one program in each language. The function with_connection opens a connection, calls the block of the caller with the connection, and closes the connection in a finally clause. It returns the value of the block. The program prints:

open db
query: 3 rows
close db
result: 3
PythonGitHub
def with_connection(name, block):
    print("open", name)
    try:
        return block(name)  # the caller's work
    finally:
        print("close", name)  # runs even if block raises


def count_rows(conn):
    rows = ["a", "b", "c"]
    print(f"query: {len(rows)} rows")
    return len(rows)


print("result:", with_connection("db", count_rows))
Output
open db
query: 3 rows
close db
result: 3
  • Verdict: native. A function takes the block as a function value. The with statement and contextlib.contextmanager give the same form.
#include <iostream>
#include <string>
#include <vector>

template <typename Block>
auto withConnection(const std::string& name, Block block) {
    struct Closer {
        const std::string& name;
        ~Closer() { std::cout << "close " << name << "\n"; }  // runs even if block throws
    } closer{name};
    std::cout << "open " << name << "\n";
    return block(name);  // the caller's work
}

int main() {
    int result = withConnection("db", [](const std::string&) {
        std::vector<std::string> rows = {"a", "b", "c"};
        std::cout << "query: " << rows.size() << " rows\n";
        return static_cast<int>(rows.size());
    });
    std::cout << "result: " << result << "\n";
}
Output
open db
query: 3 rows
close db
result: 3
  • Verdict: idiom. C++ has no finally, so a local object's destructor does the cleanup, as in RAII.
JavaGitHub
import java.util.List;
import java.util.function.Function;

public class Main {
    static <T> T withConnection(String name, Function<String, T> block) {
        System.out.println("open " + name);
        try {
            return block.apply(name); // the caller's work
        } finally {
            System.out.println("close " + name); // runs even if block throws
        }
    }

    public static void main(String[] args) {
        int result = withConnection("db", conn -> {
            List<String> rows = List.of("a", "b", "c");
            System.out.println("query: " + rows.size() + " rows");
            return rows.size();
        });
        System.out.println("result: " + result);
    }
}
Output
open db
query: 3 rows
close db
result: 3
  • Verdict: native. A method takes the block as a lambda. For an AutoCloseable resource, try-with-resources does the same work.
using System;
using System.Collections.Generic;

static T WithConnection<T>(string name, Func<string, T> block)
{
    Console.WriteLine($"open {name}");
    try
    {
        return block(name); // the caller's work
    }
    finally
    {
        Console.WriteLine($"close {name}"); // runs even if block throws
    }
}

int result = WithConnection("db", conn =>
{
    var rows = new List<string> { "a", "b", "c" };
    Console.WriteLine($"query: {rows.Count} rows");
    return rows.Count;
});
Console.WriteLine($"result: {result}");
Output
open db
query: 3 rows
close db
result: 3
  • Verdict: native. A method takes the block as a Func delegate. For an IDisposable resource, the using statement does the same work.
JavaScriptGitHub
function withConnection(name, block) {
  console.log("open", name);
  try {
    return block(name); // the caller's work
  } finally {
    console.log("close", name); // runs even if block throws
  }
}

const result = withConnection("db", (conn) => {
  const rows = ["a", "b", "c"];
  console.log(`query: ${rows.length} rows`);
  return rows.length;
});
console.log("result:", result);
Output
open db
query: 3 rows
close db
result: 3
  • Verdict: idiom. A function takes the block as a callback and closes the resource in finally.
TypeScriptGitHub
function withConnection<T>(name: string, block: (conn: string) => T): T {
  console.log("open", name);
  try {
    return block(name); // the caller's work
  } finally {
    console.log("close", name); // runs even if block throws
  }
}

const result: number = withConnection("db", (conn) => {
  const rows = ["a", "b", "c"];
  console.log(`query: ${rows.length} rows`);
  return rows.length;
});
console.log("result:", result);
Output
open db
query: 3 rows
close db
result: 3
  • Verdict: idiom. A generic parameter T gives the type of the value that the block returns.
package main

import "fmt"

func withConnection(name string, block func(conn string) int) int {
	fmt.Println("open", name)
	defer fmt.Println("close", name) // runs even if block panics
	return block(name)               // the caller's work
}

func main() {
	result := withConnection("db", func(conn string) int {
		rows := []string{"a", "b", "c"}
		fmt.Printf("query: %d rows\n", len(rows))
		return len(rows)
	})
	fmt.Println("result:", result)
}
Output
open db
query: 3 rows
close db
result: 3
  • Verdict: idiom. A function takes the block as a function value, and defer does the cleanup.
RustGitHub
fn with_connection<T>(name: &str, block: impl FnOnce(&str) -> T) -> T {
    struct Closer<'a>(&'a str);
    impl Drop for Closer<'_> {
        fn drop(&mut self) {
            println!("close {}", self.0); // runs even if block panics
        }
    }
    println!("open {}", name);
    let _closer = Closer(name);
    block(name) // the caller's work
}

fn main() {
    let result = with_connection("db", |_conn| {
        let rows = ["a", "b", "c"];
        println!("query: {} rows", rows.len());
        rows.len()
    });
    println!("result: {}", result);
}
Output
open db
query: 3 rows
close db
result: 3
  • Verdict: idiom. A closure is the block, and a value with Drop does the cleanup.

Consequences

The benefits:

  • The setup and the cleanup are in one place. Callers cannot forget the cleanup.
  • The cleanup also runs when the block raises an error, if the function uses finally or an equivalent.2
  • The function can return the value of the block. Ruby's IO.open with a block calls the block with the IO object and returns its value.3

The costs:

  • The caller must put its work in a block or a function. In a language without closures this needs an object, for example an interface with setUp, thunk and tearDown methods.1
  • The resource is available only inside the block. Code that must keep the resource open across calls cannot use this form.

If the function does not protect the cleanup, an error in the block skips it. The simple openDuring: method on the WikiWikiWeb page has this form.1 Here the file is never closed:

This code runs but gives a wrong answer on purpose.

def open_during(block):
    print("open file")
    block()
    print("close file")  # skipped when block raises


try:
    open_during(lambda: 1 / 0)
except ZeroDivisionError as e:
    print("error:", e)
Output
open file
error: division by zero

When not to use it

  • The resource must stay open longer than one call, for example a connection that a pool keeps.
  • The language has a statement for the same work, such as with in Python, using in C# or try-with-resources in Java.456 Then use the statement and write a context manager or a disposable type.
  • Language statements. Python's with statement wraps the execution of a block with methods defined by a context manager. This allows common try, except and finally usage patterns to be encapsulated for convenient reuse.4 Java's try-with-resources statement ensures that each resource is closed at the end of the statement.6 C#'s using statement disposes the IDisposable instance when control leaves the block, even if an exception occurs.5
  • Generator-based context managers. Python's contextlib.contextmanager turns a generator with setup, yield and a finally cleanup into a context manager.2
from contextlib import contextmanager


@contextmanager
def connection(name):
    print("open", name)
    try:
        yield name
    finally:
        print("close", name)


with connection("db") as c:
    print("using", c)
Output
open db
using db
close db
  • RAII. In C++, the destructor of an object runs when the object goes out of scope. The WikiWikiWeb page notes that the pattern has also been discussed under Resource Acquisition Is Initialization.1
  • Lisp with-open-file. It expands into unwind-protect around the body, with close as the cleanup form.1
  • Template Method. A template method also fixes the steps before and after a variable step, but it uses a subclass for the variable step, not a block.

Known uses

  • Ruby IO.open. The C function rb_io_s_open creates the IO object. When a block is given, it returns rb_ensure(rb_yield, io, io_close, io), so io_close runs even if the block raises.7
  • Python contextlib. The docstring of contextmanager shows that with some_generator(<arguments>) as <variable> is equivalent to setup, then try, the body, and finally with the cleanup.2

References

  1. Execute Around Method, WikiWikiWeb, whole page
  2. CPython v3.14.0 source, Lib/contextlib.py, contextmanager and its docstring, lines 276 to 306
  3. class IO, Ruby 3.4 documentation, IO.open
  4. The Python Language Reference, 8.5 The with statement, The with statement
  5. using statement, C# language reference, Microsoft Learn, first paragraphs
  6. The try-with-resources Statement, The Java Tutorials, first paragraphs
  7. Ruby v3_4_0 source, io.c, rb_io_s_open, lines 8158 to 8168

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source