Design – Are static global variables as bad as global variables? How to avoid using them

cdesignglobalsstatic

In general, I know that global variables are bad and should be avoided.
Are static global variables equally bad?

In all my projects, I have heavily relied on static global variables. From design perspective, how can I avoid using them.

Ex Use case :

Whenever the key is changed(by some other threads), my call back notifier is executed in which I update my static global variable with the new key. This key is used everywhere in the program to decrypt some data.

How can I avoid static globals in this case?

Best Answer

Whenever the key is changed(by some other threads), my call back notifier is executed in which I update my static global variable with the new key. This key is used everywhere in the program to decrypt some data.

What is trapping you in this kind of thinking is the concept of "the key". It should be "a key".

You think of the key as global so anything that would hold it must be global. Imagine your requirements change and suddenly there are 5 keys running around.

Can't imagine that? Fine, imagine 5 systems, that do nearly the same thing, that must have different keys and all need to be part of your application. How much of your code could be reused?

The key belongs in a context. Within that context there will be only one key. But that doesn't mean there will only ever be one context.

Rather than force everything to find this key by knowing "the one true key" tell them what context they are in by passing them some way to find the key they care about.

That means the key will still only be stored in one place. But now only one place decides where that place is. If you make it global then everything has to know where it is and AGREE on where that is. Ick.

Related Topic