常量和全局变量和单身人士一样邪恶吗? [英] Are constants as evil as global variables and singletons?

查看:112
本文介绍了常量和全局变量和单身人士一样邪恶吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个论坛上多次听到使用全局变量是一种死罪,实施单身人士是犯罪。



在我看来,旧常量具有所有这些耻辱行为的特征:它们是全球访问的,毫无疑问,它们引入了有史以来最全球化的状态。 >

所以,问题是:我们是否也不应该向常量声明圣战,并且一直使用DI,IoC或其他时髦词语的所有现代元素?

解决方案

全局变量被认为是不好的做法的主要原因是因为它们可以在系统的一部分中修改并在另一部分中使用,这两段代码之间没有直接的联系。



这会导致潜在的错误,因为可以编写使用全局变量的代码而无需知道(或考虑)所有使用它的地方以及它可以改变的方式。或者反之亦然,编写对全局进行更改的代码,而不会意识到这些更改可能会影响其他与您代码无关的部分。



常量不共享这个问题,因为他们......好,不变。一旦它们被定义,它们就不能被改变,因此上面描述的发布不会发生。



因此,它们可以全局使用。 / p>

也就是说,我看到一些使用 define 创建常量的PHP代码很差,但是以不同的方式声明常量在不同的情况下。这是常数的错误使用:常量应该是绝对固定的值;它应该只是一个单一的价值。如果你在程序的不同运行中可能有不同的值,那么它不应该被定义为常量。这种事情确实应该是一个变量,然后应该遵循与其他变量相同的规则。



这种错误使用只能发生在像脚本语言PHP;它不会发生在一种编译语言中,因为你只能在一个地方定义一个常量,并且定义一个固定值。


I've heard many times on this forum that using global variable is a dead sin and implementing singleton is a crime.

It just came to my mind that old good constants bear all the features of these dishonored practices: they are globally accessed and no doubt they introduce globallest state ever.

So, the question is: shouldn't we declare a jihad to constants too, and use all the modern things like DI, IoC or other stylish words all the way instead?

解决方案

The primary reason why global variables are considered bad practice is because they can be modified in one part of a system and used in another part, with no direct link between those two pieces of code.

This leads to potential bugs because it is possible to write code that uses a global variable without knowing (or considering) all the places where it is used and ways in which it could be changed. Or vice-versa, write code that makes a change to a global, without realising the impact that change may have in other unrelated parts of your code.

Constants do not share this issue, because they are... well, constant. Once they're defined, they can't be changed, and thus the issued described in the above paragraph cannot occur.

Therefore, they are fine to use globally.

That said, I have seen some poorly written PHP code that uses define to create constants, but declares the constants differently in different circumstances. This is a mis-use of constants: A constant should be an absolutely fixed value; it should only ever be a single value. If you have something that could potentially be different values on different runs through the program, then it shouldn't be defined as a constant. That sort of thing should indeed be a variable, and then should follow the same rules as other variables.

This sort of mis-use can only happen in a scripted language like PHP; it couldn't happen in a compiled language because you can only define a constant once, in one place and to a fixed value.

这篇关于常量和全局变量和单身人士一样邪恶吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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