Thursday, September 13, 2007

software engineering - maintainable global variables using stacks

problem: global variables (and static singletons) are convenient for stuff that all functions/classes probably need to access (loggers, database connections, profilers). it's painful to pass all these around as arguments. but, it can also be painful if you want to temporarily change those variables (for example, if you want to temporarily log to a different file for a certain function call).

solution: for each global variable, make a stack. so instead of declaring "int x;" declare "stack x;". when you use it, just use the top element. when you need to change it temporarily, push on a new value, and pop it after you're done.

idea from: OpenGL does exactly this, as the whole library is just global state (you NEVER pass around any GL objects). you push/pop matrices, attribute sets, etc. it works quite well and looks very clean . LISP also does this when you use 'let' and bind to a global variable. it'll push your new value, and actually pop it out for you when the 'let' expression is done (ergo, lisp is awesome).

1 comment:

Tristan said...

That's pretty cool, good idea... I've never used OpenGL before but the idea holds for pretty much any global you might use. Keeps you from messing things up like you might with a normal global.

And Lisp rocks. Peace.~