How to share constant state throughout code without globals
I have a program that uses an external API which uses its own state. The program stores the initial state at the beginning. Afterwards, dozens of functions are invoked using a dispatche开发者_如何学JAVAr depending on the input. Each of them alters the current state using the API. One of the functions should be able to reset the current state to the initial. Although, that would require access to the variable/constant set at the beginning, which is out of scope in the function.
One solution would be a global, which is considered evil. Another solution could be a function with a static variable to store the initial state at its first call. Calling it again would return the static state. Although, this is not really an improvement.
Is there any clean, maintainable solution to this problem?
Edit: OK, let's say I'll use a const global after all. To illustrate it, I'll use the following code:
extern int get_state();
extern void set_state(int);
const int initial_state = get_state();
int main()
{
while(1) {
// call dispatcher, eventually
break;
}
set_state(initial_state);
return 0;
}
The problem is that the initializer of initial_state
must be constant, which get_state()
apparently isn't. Is there any way to work around this?
Globals aren't evil (especially if constant).
Any other solution would likely be ugly and would have a better chance of introducing bugs.
You can make use of Singleton design pattern. With this you can share the common state in a cleaner and controlled manner. Here is the Code for your reference.
In State.h
State *getState(void);
In State.c
static State *g_state;
State* getState(void)
{
if(g_state == NULL) // not initialized
{
// Allocate Memory and initialize it
}
else
{
// operate on it if necessary. Can have mutex, semaphore based on your Use Case.
return g_state;
}
}
Here even though common state is a Global Variable, it is not accessible outside getState() function, hence no evil of using Global variable!!
Shash
精彩评论