Many languages have some dynamic variables (this, self), and few languages have first-class support for them (notably CL, Perl). While dynamic variables are tricky to emulate fully, as long as you have the ability to catch exceptions and closures, a very fair simulation can be made:
(function(){
var o={};
D=function(k){return o[k]}
dlet=function(b,f){
var r,s={};function oops(){for(var k in s)o[k]=s[k]};
for(var k in b)s[k]=o[k],o[k]=b[k];
try{r=f()}catch(e){oops();throw e;}; oops();return r;
};
})();
Besides feature variables that are globally accessible, one useful thing you can do with dynamic variables is set up error handlers. Consider the situation where you are saving a big file to the disk and run out of space. If you: save_stuff(); if(oops)throw 'out of space'; save_more_stuff();
then your slow saving operation needs to be retried from the start, however if you use a dynamic variable to look up the handler, you can: save_stuff(); if(oops)D('out of space')(next); else next();
function next(){ save_more_stuff(); }
The user can then use their fancy multitasking environment to clean up some space, and we can continue our operation. I generally recommend this form of error handling anyway.Another useful thing is for context: Imagine you have a user interface choice between an HTTP response and a command line interface. One way to do this is to have two applications, and another way is DI (dependancy injection: pass the "response" object around), however another way is using dynamic variables:
D("output")(...);
This has the benefit of not requiring an extra argument to all of your functions.This happens more than you might think: Many people when confronted with all their dynamic variables put them into some kind of "master object" (current logged in user, output handler, database settings, etc), however dynamic variables
When you do this, a lot of features become very easy to set:
• Capturing output (simply mock a new "output" var)
• Testing logic: dlet({db:test_settings},r)===dlet({db:live_settings},r)
• Impersonate users (if the right credentials are available)
And so on.