Documenting Global Variables [DI25] [WHAT] [WHY] [HOW] [WHERE]

Documenting Global Variables [DI25] [WHAT] [WHY] [HOW] [WHERE]

Tip DI25

Global variables - and their close cousin of “static” variables (either in a file or class) - have a large scope, making them an interface that could be used just about anywhere in a program. With such a large scope, it’s important that they be documented to ensure correct usage.

After describing what the variable itself is (represents/holds), considering documenting the following additional information:

  • The lifetime of its validity - When is it initialized, de-initialized, or otherwise expected to be valid?

  • Access patterns/restrictions - What part of the code should/shouldn’t access it?

  • Usage guidelines - What should code using this global variable to be aware of?

  • Why it’s global - Document why the data needs to be global for future maintenance programmers.

Naming conventions can also help with global variables. The following example shows how considerations for global-like variables can be documented:

“Constants” are often global (or have a relatively large scope) since one of the purposes of constants is to centralize values for re-use in multiple places. Since true constants aren’t modifiable, they don’t typically need as heavy documentation as modifiable global variables - documenting just what a global constant is may be sufficient.

 

Code in the zone ad.png