[plt-scheme] style question

From: Ryan Culpepper (ryanc at ccs.neu.edu)
Date: Sat Sep 19 13:16:42 EDT 2009

Todd O'Bryan wrote:
> I'm writing a text converter that goes through a text file and
> replaces parts of it with place-holders that I can fill back in later.
> As a result, I have to keep track of the number of parts I've replaced
> and increment the count each time I replace a new substring. If I were
> doing this as an OO program, I'd create a Converter class and have the
> number of parts so far be a field. Doing the same thing functionally,
> it seems like I have two choices--either have the counter be a
> module-level variable that all the functions have access to, or pass
> it around as a parameter to every function that needs it or calls
> other functions that need it.
> So, here's my question--which is better style in Scheme? If I don't
> provide the variable, it's not really *global* in the scary sense that
> global variables are bad, but suppose two different processes both use
> the same module at the same time. Does each get its own copy of the
> variable, or is there really only one copy that the two processes
> would share (and possibly confuse each other as a result)? Passing
> around the counter seems cleaner conceptually--all the dependencies
> are explicit--but it just feels clunky.

Module-level variables are shared across threads, so lifting local state 
to a global level is generally a bad idea.

In general, make sure the mechanisms you use to represent state in your 
program match the state you're trying to represent. Anything else 
requires careful thinking. For example, it might be safe to represent 
*task-specific* state using a *thread-local* storage mechanism. But 
you'd better be sure that tasks really match up with threads; that is, 
that tasks never hop threads, and that different tasks never nest within 
a single thread.


Posted on the users mailing list.