枚举VS类VS接口 [英] Enums VS Classes VS Interfaces

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

问题描述



问题:
什么时候应该使用枚举的常量,vs使用类或接口。



我看到我正在寻找的两个关键情况。



1。全局常数在多个项目的应用程序中使用。



示例:




  • 记录字符串

  • 容器引用,如
    中使用的数据库映射引用WebSphere EAR的



2。对象特定常量



示例:




  • 员工对象的员工薪酬



从我看过的一切,我认为我有一个把握,我在寻找什么意见。



对于情况1:
设计方法:使用最终类和静态导入。

看到这里:使用界面常数是什么?



对于情况2:
设计方法:应用使用枚举将这些常量表示为对象。



要记住的其他要点:




  • 如果常量字符串属于类并且您只需要使用字符串值保留在使用它的类中

  • 不要为情况1使用接口。如上面的链接中所述,作为常量接口反模式。



提前感谢想法和意见。

解决方案

全局常量应该实际上在属性文件中,因为它允许每个应用程序单独配置它们,而不需要代码修改。对于特定于对象的常量,我在 Enum static final 中的一般经验法则通常倾向于有多少元素有这些元素是如何相关的。如果他们之间有一个很大的关系,例如卡片的卡片中的 Suits ,那么我将去枚举。如果是用户的默认年龄,那么这将成为一个最终,因为没有任何目的使其成为一个枚举,因为它不需要在许多领域被引用。这些只是对我接近的每一种方式的一些想法。


I have been reading a lot of posts on this site regarding the usage of constants.

Question: When should I use Enums for constants, vs using classes or interfaces.

I see 2 key situations I am looking to address.

1. Global Constants used in a applications by multiple projects.

Example:

  • Common logging strings
  • Container references like a database mapping reference used in WebSphere EAR's

2. Object Specific Constants

Example:

  • Employee pay rates for an Employee Object

From everything I have read this is what I think I have a grasp on and what I am looking for an opinion on.

For situation 1: Design Approach: Use a final class and a static import.
Seen here: What is the use of interface constants?

For Situation 2: Design Approach: Apply the use of Enums to represent those constants as a object.

Additional points to remember:

  • If the constant string belongs to the class and you only need the string value keep in the class that uses it
  • Don't use an Interface for situation 1. As mentioned in the link above as Constant Interface Anti-pattern. .

Thanks in advance for thoughts and opinions.

解决方案

Global constants as you put it should actually be in a properties file as it allows each application to configure them individually without a code modification. For object specific constants my general rule of thumb on Enum versus static final I typically lean towards how many elements there are to have and how related those elements are. If there is a big relation between them such as Suits in a deck of Cards then I would go for the enum. If it is default age for a user, then this becomes a final as there is no purpose to making it an enum as it would not need to be referenced in many areas. These are just some thoughts on each of the ways I have approached it.

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

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