一、 编程中的魔数
在阿里巴巴Java开发手册编程规约第二节常量定义的第一条中写道:
魔法值(即魔数)指的是未经预先定义的常量,而反例中的 “Id#taobao_” 则叫做魔字符串(Magic String)。这一规定在《Clean Code》和各大公司的代码规范手册中都有被提及过,那为什么这样规定呢?
《计算机程序的构造和解释》一书中表达过这种观点:
代码的第一要义是供人类理解,其次才是能正确地被机器执行。
没有一个程序猿愿意去读不带注释的代码,注释是一个好东西,但谁愿意为他代码中每一个常量后边加上注释?加得不累?我们看着累!公司里的一个项目基本都是多人合作,多组交接完成,谁也不希望在接手上一任的摊子前先要花几天去读明白他写的代码,因此,良好的代码规范,是每一位程序猿所必要的,用静态变量、枚举、宏定义等方法去避免代码中出现魔数,大大提高代码的可读性,让你的合作伙伴不再动不动就拿着你的小人扎你。
二 、文件中的魔数
文件中的魔数是为了确定文件的类型,许多格式的文件都有魔数,比如bmp中的“BM”、JPEG/JFIF中的“JFIF”,另外一些音频、视频格式的文件一样有魔数,Java也不例外。下面是一个简单的Java文件
public class MagicNumber {
public static void main(String[] args) {
System.out.println("Cafe Babe");
}
}
在当前目录shift+鼠标右键打开 Power Shell,用javac编译该java文件,并在Emacs里按Alt+X输入hexl mode 以16进制模式打开class文件:
如图
- 前四个字节cafebabe就是Class文件的魔数
- 5、6字节为Class文件的次版本号
- 7、8字节为Class文件的主版本号,0034,即十进制的52.0对应JDK 1.8.0
We used to go to lunch at a place called St Michael’s Alley. According to local legend, in the deep dark past, the Grateful Dead used to perform there before they made it big. It was a pretty funky place that was definitely a Grateful Dead Kinda Place. When Jerry died, they even put up a little Buddhist-esque shrine. When we used to go there, we referred to the place as Cafe Dead. Somewhere along the line it was noticed that this was a HEX number. I was re-vamping some file format code and needed a couple of magic numbers: one for the persistent object file, and one for classes. I used CAFEDEAD for the object file format, and in grepping for 4 character hex words that fit after “CAFE” (it seemed to be a good theme) I hit on BABE and decided to use it. At that time, it didn’t seem terribly important or destined to go anywhere but the trash-can of history. So CAFEBABE became the class file format, and CAFEDEAD was the persistent object format. But the persistent object facility went away, and along with it went the use of CAFEDEAD - it was eventually replaced by RMI. 0xCAFEBABE’s decimal number is 3405691582. If we add up all the bits we get 43. Exactly greater than 42-Ultimate Answer to the Life, the Universe, and Everything. The other 43 is also a prime number. You see, magic everywhere. Even in the last sentence.