Global variables (again)

前端 未结 11 964
感情败类
感情败类 2021-01-21 16:31

I keep hearing that global variables should never be used, but I have a tendency to dismiss \"never\" rules as hot-headed. Ar

11条回答
  •  抹茶落季
    2021-01-21 16:43

    • Global variables can change in unexpected ways, which is usually not what you want. The state of the application will become complex and unmaintainable. Very easy to make something wrong. Especially if someone else is changing your code;

    • Singleton might be a better idea. That would at least give you some encapsulation in case you need to make extensions in the future.

    • One reason not to use global variables is a problem with namespaces (i.e. accidentally using the same name twice);

    • We do often use global (to namespace) constants at work which is considered normal, as they don't change (in unexpected ways) and it is very convenient to have them available in multiple files.

提交回复
热议问题