命名编号为变量 [英] Named numbers as variables

查看:152
本文介绍了命名编号为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个几次,最近的高调的代码,其中常量定义为变量,数值命名,那么只能使用一次。我不知道为什么它能够完成?



例如。 Linux的源代码(resize.c)

 无符号5 = 5; 
无符号7 = 7;



例如。 C#.NET源代码(Quaternion.cs)

 双零= 0; 
双一= 1;


解决方案

命名的数字是可怕的做法,总有一天会有需要改变,你会结了无符号5 = 7



如果它有一定的意义,给它一个有意义的名字。在幻数五类是在神奇数字 5 ,这是糟糕的,因为它可能实际上并不等于没有起色 5



这种事情通常源于一些货物邪教式的编程风格指南如果有人听说过魔法数字是坏,并禁止其使用没有完全理解这是为什么。


I've seen this a couple of times recently in high profile code, where constant values are defined as variables, named after the value, then used only once. I wondered why it gets done?

E.g. Linux Source (resize.c)

unsigned five = 5;
unsigned seven = 7;

E.g. C#.NET Source (Quaternion.cs)

double zero = 0;
double one = 1;

解决方案

Naming numbers is terrible practice, one day something will need to change, and you'll end up with unsigned five = 7.

If it has some meaning, give it a meaningful name. The 'magic number' five is no improvement over the magic number 5, it's worse because it might not actually equal 5.

This kind of thing generally arises from some cargo-cult style programming style guidelines where someone heard that "magic numbers are bad" and forbade their use without fully understanding why.

这篇关于命名编号为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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