简体   繁体   English

魔术数字不需要命名常量的情况

[英]A case where named constants are not needed over magic numbers

Obviously the point of using named constants over magic numbers is for code clarity and for not having to go through code changing numbers throughout. 显然,在魔术数字上使用命名常量的目的是为了使代码清晰,而不必遍历整个代码更改数字。

However, what do you do if you just have a number used just once in a function? 但是,如果函数中只使用了一个数字,该怎么办? Say you have a short member function that uses an object's velocity (which we'll say won't change) to calculate its motion, but this is the only function that uses that velocity. 假设您有一个短成员函数,该函数使用对象的速度(我们将说不会改变)来计算其运动,但这是唯一使用该速度的函数。 Would you... 你会...

A) Give the class a named static constant to use A)给该类命名的静态常量以供使用

B) Put a named constant in the function B)在函数中放置一个命名常量

C) Use the magic number but comment it C)使用幻数但要注释

D) Other... D)其他...

I am kind of leaning towards using a magic number and commenting it if the number is ONLY BEING USED ONCE, but I'd like to hear others' thoughts. 我倾向于使用一个魔术数字,如果该数字仅可使用一次,请对其进行评论,但我想听听其他人的想法。

Edit: Does putting a named constant in a function called many times and assigning to it have performance implications? 编辑:将命名常量放入多次调用的函数中并对其进行赋值是否会对性能产生影响? If it does I guess the best approach would be to put the constant in a namespace or make it a class variable, etc. 如果可以的话,我猜最好的方法是将常量放入名称空间或使其成为类变量,等等。

Just move it up: 只需向上移动:

void do_something(void)
{
    const float InitialVelocity = 5.0f;

    something = InitialVelocity;
    // etc.
}

Say you have a short member function that uses an object's velocity 假设您有一个使用成员速度的短成员函数

You said it, the constant has a name: 你说了,常量有个名字:

const type object_velocity = ....;

Magic numbers are my enemies :) 魔术数字是我的敌人:)

I'd use a function-local named constant, at a minimum. 我至少要使用局部函数命名常量。 Usually I'd use an anonymous namespace named constant to make the value available throughout the source file, assuming that it might be useful later to other functions. 通常,我会使用一个名为constant的匿名命名空间来使该值在整个源文件中都可用,假设它以后可能对其他函数有用。

使用Eclipse重构函数将常量移动到方法的命名变量中。

在函数内部将其用作常量:

const int x = myMagicNumber; //Now document the magic.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM