ok , global variable is condemned, singleton is despised, what's the alternative?

Solution 1:

A static class with static data members? But who cares. Static data members are just global variables with more politically correct packaging.

Don't let fashion override your common sense. There's nothing wrong with using a plain old global variable. The singleton pattern is often overkill and annoying to type, and annoying when you are single stepping through code to debug it.

Assuming you are using C/C++, I would recommend that you not have global variables that are class instances that allocate memory from the heap. They will make it harder for you to use tools that check for memory leaks. Declare the global as a pointer, new it at the beginning of main(), delete it at the end.

EDIT AFTER 6 COMMENTS: Think of logging. Wouldn't you want to be able to write a line to your log from anywhere in your app? How concretely do you accomplish that without there being something globally visible to do that logging? If you want something globally visible, then go ahead and make it globally visible.

Solution 2:

Answer depends on the language. I recently met a guy whose company develops the USB stack that runs on many popular cell phones (e.g., so your phone can talk to your computer). They have a rule in their shop that all C procedures must be reentrant. In practice what this means is that instead of global variables, they use an extra parameter to each routine; the parameter points to the state that should persist between routines.

I use this technique all the time for abstractions with state. Example: reader abstraction for photographic images: reader provides access to one pixel at a time; it must know open file descriptor, what is the current position in the image, so on and so forth. All that information goes into a private C struct or the private members of a C++ class. No global variables. The outside world sees:

typedef struct Pnmrdr_T *Pnmrdr_T;

struct Pnmrdr_T *Pnmrdr_new(FILE *);
pixel Pnmrdr_get(Pnmrdr_T);
void Pnmrdr_close(Pnmrdr_T);
void Pnmrdr_free(Pnmrdr_T *rp); // frees memory and sets *rp = NULL

This style of programming is very similar to OO methods.

Why better than global variables? There are no surprises. If something goes wrong or you want to add a feature, you know that everything is explicit in values passed in. Moreover, you know you can plug lots of modules together and they won't interfere unless you explicitly pass state between them. My contact in the cellphone biz says this property has been huge for his company---they're an OEM software outfit and they can easily plug different pieces together for different clients.

I really like programming this way because I get to see everything that's going on, and my private data structures are protected from prying eyes :-)