Alternatives for global variables

Asked

Viewed 149 times

2

What would be the best practices to avoid the use of global variables? How to save the logged in user or a file name that will be accessed in several places for example?

1 answer

3


The design should reduce the need for comprehensive data

If there is a need to make use of a filename at various points in the code, then access to the contents of this file is probably not localized but dispersed. If this is the case, then the suggestion is to refactor the code to concentrate this dispersed use in a single file, possibly in a single class, possibly in a single routine or method.

Note that if it is not just the file name, but several other data whose access occurs at various points in the code, then almost certainly the code in question is highly coupled. As a consequence, if possible, if feasible, the code should pass through a refactoring effort and reduce this "technical speed".

Finally, underlying the preceding paragraphs is the premise that such "global data introduces a non-essential complexity", that is to say it was created, probably without the intention of complicating, but it is an accidental complexity, not arising from the problem in question, but the option of design of the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.