为什么全局变量被认为是不良做法? (的node.js) [英] Why are global variables considered bad practice? (node.js)

查看:100
本文介绍了为什么全局变量被认为是不良做法? (的node.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前遇到的问题是我有两个模块,我调用它需要能够修改同一个变量。

我决定创建一个名为 global.APP_NAME = {} 并存储我需要的变量。

I'm currently face with a problem where I have two modules that I call that need to be able to modify the same variable.
I decided to create a global variable called global.APP_NAME = {} and store the variables that I need in that.

但我一直在读,使用全局变量是不好的做法。为什么?

But I have been reading that it is bad practice to use global variables. Why is it?

我只创建一个变量,不应该碰到其他任何变量,因为它是我的应用程序的名称。

I am only creating one variable, that should not collide with anything else because it is the name of my application.

推荐答案

几乎所有编程语言都认为全局变量是一种反模式,因为它们很难跟踪和调试代码。

Global variables are considered an anti-pattern in almost any programming language because they make it very hard to follow and debug code.


  • 当您浏览代码时,您永远不知道哪个函数设置或使用全局变量。当所有变量都是局部变量或传递给函数时,您可以确定函数的副作用是有限的。

  • 全局变量在远处工作。拧入全局值可能会在应用程序的完全不同部分产生意外影响。当您调试由此引起的错误时,您将很难找到变量更改为错误值的位置。

  • 全局变量共享命名空间,因此您可能无意中重用虽然你不打算这样做。

  • 很难说全局变量有多重要。你永远不会知道它是仅仅由两个函数使用,还是它的价值在整个地方都很重要。

  • ......以及更多原因......

  • When you browse the code, you never know which function sets or uses a global variable. When all variables are either local or passed to a function, you can be sure that the side-effects of the function are limited.
  • Global variables work at a distance. Screwing with the value of a global could have unexpected effects in a completely different part of the application. When you debug an error caused by that, you will have a very hard time finding out where the variable was changed to a wrong value.
  • Global variables share a namespace, so you can inadvertently reuse them although you don't intend to do so.
  • It's hard to tell how important a global variable is. You never know if it's used by just two functions or if its value is important all over the place.
  • ...and many more reasons...

当你有两个共享数据的模块时,你应该创建一个包含该数据的对象并将其显式传递给需要它的每个函数(并且只有那些实际执行的函数) 。

When you have two modules which share data, you should create an object with that data and explicitly pass it to each function which needs it (and only those which actually do).

这篇关于为什么全局变量被认为是不良做法? (的node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆