[英]Java enum initialization best practices
I have a question regarding best practices when dealing with enums in Java. 我在处理Java枚举时有关于最佳做法的问题。 Let's say I have a java class and an enum class like so: 假设我有一个Java类和一个枚举类,如下所示:
public class Foo {
private final FooEnum fooEnum;
public Foo(FooEnum fooEnum) {
this.fooEnum = fooEnum;
}
public Foo(String fooEnum) {
this.fooEnum = FooEnum.valueOf(fooEnum);
}
}
public enum FooEnum {
FOO1,
FOO2,
FOO3
}
My question is this: Is it considered good practice to offer a 2nd constructor that takes in a string to initialize the enum so the user can choose either to pass an enum or it's string equivalent? 我的问题是:提供一个第二个构造函数,该构造函数接受一个字符串来初始化枚举,以便用户可以选择传递枚举还是等效的字符串,这是否被认为是一种好习惯? If not, what is the alternative? 如果没有,那有什么选择呢? Should the user be responsible for converting the string into an enum? 用户应该负责将字符串转换为枚举吗?
No, it is bad practice to do that: 不,这样做是不好的做法:
FooEnum
for a string, is it that bad to say new Foo(FooEnum.valueOf(str))
? 而且,如果确实需要为字符串获取FooEnum
,那么说new Foo(FooEnum.valueOf(str))
好吗? What if I pass in the string "bibble": it's not a problem in Foo
that causes the exception to be thrown, so don't involve Foo
in that problem. 如果我输入字符串“ bibble”怎么办:在Foo
,引发异常的问题不大,所以不要让Foo
参与该问题。
By providing a String
constructor, you are saying that "you can pass me any string" (of which there are practically infinitely many); 通过提供一个String
构造函数,您说的是“您可以向我传递任何字符串”(实际上,字符串可以无限多); by providing a FooEnum
constructor, you are saying that "you can pass me any FooEnum
", of which there are a very small number. 通过提供FooEnum
构造函数,您说的是“您可以将任何FooEnum
传递给我”,其中有一个很小的数目。 So you're limiting the space of valid inputs substantially; 因此,您实际上在限制有效输入的空间; and the user isn't left guessing what a valid input might be. 用户不必猜测有效输入可能是什么。
The alternative: since you need an instance of FooEnum
in your Foo
, make the user of the class pass in an instance of FooEnum
. 另一种选择:由于您在Foo
需要FooEnum
的实例, FooEnum
请让该类的用户传递FooEnum
的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.