魔抓编程
In some tutorials, books, or videos, you might have seen the term magic number.
在某些教程,书籍或视频中,您可能已经看到了魔术数字一词。
What is that?
那是什么?
When is a number magic?
什么时候是数字魔术?
Unfortunately magicians have nothing to do with magic numbers.
不幸的是,魔术师与魔术数字无关。
Simply put, we say that a number is magic when it has no meaning associated.
简而言之,我们说数字没有意义时就是魔术。
It might be an undocumented number passed to function. Or a number being declared in your code, maybe added by a team member, that you don’t really know what it means.
它可能是传递给函数的无证件编号。 或者在您的代码中声明了一个数字,也许是由团队成员添加的,您实际上并不知道这意味着什么。
What happens if you change it? No one knows.
如果更改它会怎样? 没人知道。
It’s up to experimentation to find out.
有赖于实验才能找出答案。
Those numbers are really annoying. You should avoid creating magic numbers in your code.
这些数字实在令人讨厌。 您应该避免在代码中创建幻数。
Declare a constant, with a meaningful name, and use that instead of a magic number.
声明一个具有有意义名称的常量,并使用该常量代替魔术数字。
For example:
例如:
const int PIN_ID = 1;
doSomething(PIN_ID);
is much better, and self-documenting, compared to:
相较于:
doSomething(1);
魔抓编程