【问题标题】:Is it okay to create constant variables just for the sake of readability? [closed]仅仅为了可读性而创建常量变量可以吗? [关闭]
【发布时间】:2020-05-30 05:58:32
【问题描述】:

想象一下,如果我有这段代码:

System.out.println("Is the product:\n"+
                    "1. National.\n"+
                    "2. International.");
int choice = input.nextInt(System.in);
if (choice == 1)
    (...)
else if (choice == 2)
    (...)

那么可以进行以下操作吗?

final int NATIONAL = 1;
final int INTERNATIONAL = 2;
System.out.println("Is the product:\n"+
                        "1. National.\n"+
                        "2. International.");
int choice = input.nextInt(System.in);
if (choice == NATIONAL)
    (...)
else if (choice == INTERNATIONAL)
    (...)

我不知道,我刚买了 Bob 叔叔的 Clean Code 书,我开始质疑自己。

【问题讨论】:

  • 为什么会不好?在我看来,这取决于上下文。在你的例子中它是完美的。如果您有 37 像素的边距,我会感到困惑。
  • 好吧,IDK,如果它消耗更多的内存或任何东西。
  • 是的,没关系。确实,很多人都推荐这是一种很好的做法。

标签: java coding-style


【解决方案1】:

我相信常量比 magic 数字更好。
使用常量,您可以在一处控制定义并更好地命名。它会影响您对代码的进一步可维护性。
并尝试在某些情况下使用enum 而不是常量。 Enum 的优点多于常数。
在这种情况下,枚举示例类似于以下代码:

enum UserInput {
    NATIONAL(1), INTERNATIONAL(2), UNKNOWN(-1);

    private int input;

    public int getInput() {
        return input;
    }

    UserInput(int i) {
        this.input = i;
    }

    public static UserInput getUserInput(int input) {
        for (UserInput userInput: UserInput.values()) {
            if (userInput.getInput() == input) {
                return userInput;
            }
        }
        return UNKNOWN;
    }
}

//main
public static void main(String[] args) {
        System.out.println("Is the product:\n"+
                "1. National.\n"+
                "2. International.");
        Scanner sc = new Scanner(System.in);
        int choice = sc.nextInt();
        switch (UserInput.getUserInput(choice)) {
            case NATIONAL: break;
            case INTERNATIONAL: break;
            default:
        }
    }


查看更多:Why use Enums instead of Constants? Which is better in terms of software design and readability

【讨论】:

  • 我决定使用常量,因为如果存在用户输入,我真的不知道如何使用枚举。
  • @SebastianArrieta,在这种情况下,我使用枚举示例更新代码。我希望它可以帮助你学习enum。它在 Java 中非常有用。
【解决方案2】:

当您想要一些变量(常量)或编码多个时,您可以制作常量以获得更好的可读性和理解性。 例如 -: 如果(选择==国家) (...) 否则如果(选择 == 国际) (...)

当您必须多次使用 INTERNATIONAL 和 NATIONAL 时是正确的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2018-02-10
    • 2022-06-22
    相关资源
    最近更新 更多