Search code examples
global-variablescommon-lisp

Using Local Special Variables


For prototyping convenience I've relied on a number of global variables which are heavily used throughout the code. But now I'd like to make some of them local (but dynamic). Is there any significant downside (eg, efficiency, something else) to declaring them locally special instead of global?


Solution

  • Unpopular features of special variables include:

    • Lack of referential transparency

    This makes it harder to reason functionally about your code. It means that your function produces different results with syntactically equivalent calls.

    • Introduce bugs

    If a lexical variable is defined somewhere in your code (eg. in a system function), you will overwrite it and cause bugs.

    • Confusing

    Special (dynamic) binding is unpopular, and will confuse your readers who are not familiar with it.

    • Unnecessary

    Just use lexical binding, or even anaphoric macros instead.

    More information:

    Anaphoric macros See Let Over Lambda by Doug Hoyte, or Paul Graham's anaphoric macros.

    LiSP (Lisp in Small Pieces) has a section on binding and dynamic binding

    Elisp has dynamic binding by default, and enforced dynamic binding for a long time

    Many early lisps had dynamic binding, but dropped it.