Thursday, December 06, 2018

Avoid Global Variables

Global variables make it hard to find out what code broke the system.


Global variables make it convenient to write programs; after all, if you need to access or change x, you just do it. Unfortunately, if x is ever accessed and found to have an inappropriate value, it is difficult to determine which software component is at fault. "Global" implies that anybody could have altered its value incorrectly.

As an alternative, encapsulate important data in its own module, so that anybody who wants to change it or access it must do so by means of that routine. Alternatively, explicitly pass parameters to routines that need specific data. If you find an excessive number of parameters, perhaps your design needs to be reworked.


Reference:
Ledgard, H., Programming Practice, Vol II, Reading, MA: Addison-Wesley, 1987.