幻数问题的解决方案......? [英] Solution for Magic Number issue......?

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

问题描述

考虑以下代码段...

 public static UserStatus getEnum(int code) {
    switch (code) {
        case 0:
            return PENDING;
        case 1:
            return ACTIVE;
        case 2:
            return SUSPENDED;
        case 3:
            return DELETED;
        case 4:
            return LOGIN_DISABLED;
        default:
            return null;
        }

}

现在,SONAR 将案例(案例 3 和案例 4)中的 3 号和 4 号检测为幻数.

Now number 3 and 4 in cases(case 3 and case 4) are detected as magic numbers by SONAR.

为避免该问题,我将代码段更改如下...

To avoid that issue I changed my code segment as follows...

 public static UserStatus getEnum(int code) {        
    final int Pending=0;
    final int Active=1;
    final int Suspended=2;
    final int Deleted= 3;
    final int Login_details=4;

    switch (code) {
        case Pending:
            return PENDING;
        case Active:
            return ACTIVE;
        case Suspended:
            return SUSPENDED;
        case Deleted:
            return DELETED;
        case Login_details:
            return LOGIN_DISABLED;
        default:
            return null;
    }
}

在这种情况下,这是解决幻数问题的好方法吗?

Is this a good way to solve the magic number issue in this kind of scenario ?.

推荐答案

我猜你想避免在代码中使用整数文字.您的解决方案不是特别有效,因为它只是将文字移动到方法的顶部.它获得了一点好处,因为它为常量赋予了有意义的名称,但这些名称是方法私有的.

I gather that you want to avoid using integer literals in the code. Your solution is not particularly effective because it simply moves the literals to the top of the method. It gains a little bit because it gives meaningful names to the constants, but these names are private to the method.

更好的方法是将数字定义为接口中的字段.然后,您可以静态导入字段并将它们用作常量的符号名称.

A better approach would be to define the numbers as fields in an interface. You can then statically import the fields and use them as symbolic names for the constants.

如果枚举的声明顺序与常量相同:

If the enum is declared in the same order as the constants:

enum UserStatus {PENDING, ACTIVE, SUSPENDED, DELETED, LOGIN_DISABLED}

你可以做另一个技巧:

public static UserStatus getEnum(int code) {
    UserStatus[] values = UserStatus.values();
    return (code >= 0 && code < values.length) ? values[code] : null;
}

但是,这会在常量值和枚举声明之间建立联系.这可能没问题,具体取决于在调用 getEnum 时生成实际参数值的位置.

However, this creates a linkage between the constant values and the declaration of the enum. This may be okay, depending on where the actual parameter values are generated in calls to getEnum.

这篇关于幻数问题的解决方案......?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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