什么是幻数,为什么不好呢? [英] What is a magic number, and why is it bad?

查看:79
本文介绍了什么是幻数,为什么不好呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是幻数?

为什么应该避免?

在某些情况下合适吗?

推荐答案

魔术数字是代码中数字的直接用法.

A magic number is a direct usage of a number in the code.

例如,如果您拥有(使用Java):

For example, if you have (in Java):

public class Foo {
    public void setPassword(String password) {
         // don't do this
         if (password.length() > 7) {
              throw new InvalidArgumentException("password");
         }
    }
}

这应该重构为:

public class Foo {
    public static final int MAX_PASSWORD_SIZE = 7;

    public void setPassword(String password) {
         if (password.length() > MAX_PASSWORD_SIZE) {
              throw new InvalidArgumentException("password");
         }
    }
}

它提高了代码的可读性,并且更易于维护.想象一下我在GUI中设置密码字段大小的情况.如果我使用幻数,则每当最大大小更改时,我都必须在两个代码位置中进行更改.如果我忘记了一个,将会导致不一致.

It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.

JDK充满了IntegerCharacterMath类中的示例.

The JDK is full of examples like in Integer, Character and Math classes.

PS:诸如FindBugs和PMD之类的静态分析工具会检测代码中幻数的使用并提出重构建议.

PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.

这篇关于什么是幻数,为什么不好呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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