Delegate Usage : Business Applications

后端 未结 8 1237
青春惊慌失措
青春惊慌失措 2021-01-03 02:46

Background

Given that \'most\' developers are Business application developers, the features of our favorite programming languages are used in the context of what we

8条回答
  •  [愿得一人]
    2021-01-03 03:11

    One common pattern I've seen over the years (in various languages) is to "freeze" the result of a decision to move logic out of a loop into a setup. In pseudo-code (because the technique varies with language):

    some_condition = setup_logic
    ...
    while (not terminated) {
        data = obtain_data
        if (some_condition)
            process_one (data)
        else
            process_two (data)
    }
    

    The point is that if some_condition doesn't change based on anything in the loop, then there's really no benefit from repeatedly testing it. Delegates/closures/etc. allow the above to be replaced by this:

    some_condition = setup_logic
    if (some_condition)
        selected_process = process_one
    else
        selected_process = process_two
    ...
    while (not terminated) {
        data = obtain_data
        selected_process (data)
    }
    

    (Of course, a Real Functional Programmer would have written the setup as:

    selected_process = if (some_condition) process_one else process_two
    

    ;-)

    This generalizes nicely to multiple alternatives (instead of just two). The key idea is to decide in advance what action to take at a future point (or points), and then remember the chosen action rather than the value on which the decision was based.

提交回复
热议问题