What are the advantages of dynamic scoping?

后端 未结 10 954
迷失自我
迷失自我 2020-12-14 01:21

I\'ve learned that static scoping is the only sane way to do things, and that dynamic scoping is the tool of the devil, and results only from poor implementations of interpr

10条回答
  •  忘掉有多难
    2020-12-14 01:38

    The primary risk with dynamic scope is unintended consequences. Dynamic scoping makes scope follow the runtime stack, which means that the set of symbols in scope is much larger and far from obvious at the point of any symbol usage. Dynamically scoped variables are a lot like global variables, only there may be more than one version of each variable with only the latest definition visible, hiding all the others.

    Dynamic scope, in so far as it is useful, it is useful for behaviour that needs to be sensitive to the runtime stack. For example (and speaking generally, not specific to Lisp or variants):

    • exception handling - the top-most catch block is the one that is "in scope" when an exception occurs
    • security - .NET code-based security makes decisions on the accessibility of certain privileged APIs based on what code called it.

    The problem with relying on it for other uses is that it creates implicit dependencies and coupling between lexically distant pieces of code. In this way, it's also similar to global variables, only it can be worse (due to dynamically overridden definitions).

提交回复
热议问题