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 interpreters/compilers.
Then I saw this snippet from a Common Lisp vs. Scheme article:
Both Lexically and Dynamically Lexical scope only, per the standard. scoped special vars. Common Dynamically scoped vars are provided Lisp just wins on this point. by some implementations as an extension but code using them is not portable. (I have heard the arguments about whether Dynamic scoping is or is not a Bad Idea in the first place. I don't care. I'm just noting that you can do things with it that you can't easily do without it.)
Why does Common Lisp "just win on this point"? What things are easier to do with dynamic scoping? I really can't justify ever needing it / seeing it as a good thing.
Static scoping also makes it much easier to make a modular code as a programmer can figure out the scope just by looking at the code. In contrast, dynamic scope requires the programmer to anticipate all possible dynamic contexts.
Advantages of static scoping: Readability. Locality of reasoning. Less run-time overhead.
Examples of languages that use dynamic scope include Logo, Emacs Lisp, LaTeX and the shell languages bash, dash, and PowerShell. Dynamic scope is fairly easy to implement.
Under dynamic scoping, a variable is bound to the most recent value assigned to that variable, i.e., the most recent assignment during the program's execution. In the example above, the free variable x in the body of f is evaluated when f(0) is called on line 5.
Like everything else, Dynamic Scoping is merely a tool. Used well it can make certain tasks easier. Used poorly it can introduce bugs and headaches.
I can certainly see some uses for it. One can eliminate the need to pass variables to some functions.
For instance, I might set the display up at the beginning of the program, and every graphic operation just assumes this display.
If I want to set up a window inside that display, then I can 'add' that window to the variable stack that otherwise specifies the display, and any graphic operations performed while in this state will go to the window rather than the display as a whole.
It's a contrived example that can be done equally well by passing parameters to functions, but when you look at some of the code this sort of task generates you realize that global variables are really a much easier way to go, and dynamic scoping gives you a lot of the sanity of global variables with the flexibility of function parameters.
-Adam
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With