我应该传递一个枚举作为参数还是传递它的字面值
在设计一些接口和类时,我一直在思考是否应该将枚举作为参数或其字面值传递。
在这个节骨眼上,我完全赞成传递它的字面值,因为我在某处读过我不记得传递枚举的耦合问题。
有人对此有什么意见吗? :)
public enum Item{
CANDY("candy"), APPLE("apple");
}
通过枚举传递
公开购买(物品物品){}
通过文字值传递
公开购买(String itemValue){}
干杯。
i was thinking along the line when design some interfaces and classes whether i should be passing enum as a parameter or its literal value.
At this juncture, i am all for passing its literal value as i have read somewhere i could not remember about coupling issues passing the enum.
Does anyone have any opinion on this? :)
public enum Item{
CANDY("candy"), APPLE("apple");
}
Pass by enum
public buy(Item item){}
Pass by literal value
public buy(String itemValue){}
Cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议传递枚举值,因为它的类型更强。在您的示例中,如果“candy”和“apple”是“buy”方法的唯一有效参数,您可以在编译时通过要求枚举而不是字符串作为方法参数来强制执行此操作。
I would recommend passing the enum value as it is more strongly typed. In your example, if "candy" and "apple" are the only valid arguments to the 'buy' method, you can enforce that at compile time by requiring the enum rather than the String as the method argument.
肯定会经过枚举。我的理由是:
buy
的实现中使用枚举对象比使用字符串要容易得多。例如,如果您确实需要进行切换等。String
时,则不太容易查看。buy
的实现时,您将能够轻松了解每个不同枚举值的处理方式。当您将其作为String
传递时,您可能不知道查看该方法所有可能的输入值是什么以及如何处理它们。Definitely pass by enum. My reasons being:
buy
. For example, if you do need to do switch etc.String
.buy
later on, you'll easily be able to see how each of the different enumeration values are handled. When you pass it as aString
, you might not know looking at the method what all the possible input values are and how they are handled.在大多数情况下,我会传递实际的枚举类型(本例中为
Item
)而不是字符串表示形式。这可以确保正确的键入,这也是枚举的目的。您可能希望传递字符串表示形式(从
Enum.name()
获得)的一种情况是由于序列化/版本控制问题。例如,如果您有一个应用程序的多个实例正在运行,并且您不能始终确保它们运行相同的版本,您可能只想在它们之间传递字符串表示形式,并尝试手动反序列化它们(使用
valueOf()
) 并以这种方式处理任何差异。In most cases, I would pass the actual Enum type (
Item
in this example) rather than a String representation. This ensures proper typing and is the purpose of Enums.One situation where you might want to pass the String representation (obtained from
Enum.name()
) is due to serialization/versioning issues.For example, if you have several instances of an application running and you can't always be sure they are running the same versions, you may want to just pass the String representation between them, and attempt to manually deserialize them (using
valueOf()
) and handle any differences that way.枚举是类,但具有一组预定义值。因此,您必须声明枚举并为其实例提供一个变量。
试试这个例子:
Enums are classes but with a set of predefined values. As such you must both declare the enum and give a variable for its instance.
Try this example :