When writing scripts using a modern scripting language, e.g. Powershell or JavaScript, where should I define constants? Should I make all constants global for readability and ease of use, or does it make sense to define constants as close to their scopes as possible (in a function, for instance, if it’s not needed elsewhere)? I’m thinking mostly of error messages, error IDs, paths to resources or configuration options.
Consts are good for just giving descriptive variable names to avoid the magic number problems, but they cause a similarly annoying problem of not being able to identify the value actually being used when the const is defined away from it’s use.
My suggestion, in all languages: define consts in as close a scope as possible to their actual usage. If used in only one class; only put in that class. Multiple classes would mean make sure it’s at least in the same namespace as all classes using it.
In javascript this means as close lexically in scope as it can be to all usages.
4
Instead of using constants, you could use a configuration file. JavaScript allows you to have easily parsable files in json format. I don’t know about PowerShell.
Configuration files have the advantage of being centralized, yet the name of the property in the function scope (when you retrieve it) allows you to maintain readability.
1