What is the “Execute Around” idiom?

后端 未结 8 1344
不思量自难忘°
不思量自难忘° 2020-11-22 12:39

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?

8条回答
  •  情深已故
    2020-11-22 13:13

    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.

提交回复
热议问题