What is the “Execute Around” idiom?

后端 未结 8 1338
不思量自难忘°
不思量自难忘° 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条回答
  •  -上瘾入骨i
    2020-11-22 13:20

    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.

提交回复
热议问题