唯一的枚举成员值 [英] Unique enum member values

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

问题描述

我的问题:我想在两个枚举之间指定1到1的连接。基本上:

My problem: I want to specify a 1 to 1 connection between two enums. basically:

enum MyEnum{

    ENUM_VALUE_1,
    ENUM_VALUE_2,
    ENUM_VALUE_3,

}

enum MyOtherEnum{

    OTHER_ENUM_VALUE_1(MyEnum.ENUM_VALUE_3),
    OTHER_ENUM_VALUE_2(MyEnum.ENUM_VALUE_1),
    OTHER_ENUM_VALUE_3,
    OTHER_ENUM_VALUE_4(MyEnum.ENUM_VALUE_2),

    private MyEnum pair;

    MyOtherEnum(MyEnum pair){
        this.pair=pair;
    }

}

鉴于此代码,什么是最好的方法是确保 MyOtherEnum 的两个实例没有相同的 MyEnum 对?我想到了一些解决方案,但似乎都不好。一种解决方案是在构造函数中抛出异常,但我不确定这是否可行。另一个解决方案是一个特殊的getter方法,但它可以通过简单的 MyOtherEnum.values()调用轻松绕过。

Given this code, what is the best way to make sure, that two instances of MyOtherEnum doesn't have the same MyEnum pair? I figured some solutions, but neither seem to be good. One solution is throw an exception in the constructor, but I'm not sure if that is even doable. Another solution is a special getter method, but it can be easily bypassed with simple MyOtherEnum.values() calls.

推荐答案

听起来你不应该把它作为运行时检查来实现。只有控制代码的开发人员做了一些不好的更改,它才会失败。检测引入错误的更改是测试的目的。

It sounds like you shouldn't implement this as a runtime check. It can only fail if a developer who has control over the code did some bad changes. Detecting changes that introduce bugs is what tests are for.

编写一个简单的测试,检查一切是否正确。其他答案已经提供了一些很好的解决方案来检查重复的枚举。而不是运行应用程序以查看枚举初始化是否失败,运行测试(我希望您已经编写并运行测试)。

Write a simple test that checks if everything is correct. The other answers already provide some good solutions to check for duplicated enums. Instead of running the application to see if the enum initialisation fails, run the test (I hope you already write and run tests anyway).

这篇关于唯一的枚举成员值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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