仅与常量接口 [英] Interface with only constants

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

问题描述

最近我遇到了一段代码,其中我找到了一个只有 常量的界面。并且使用静态导入在类中访问这些常量。常数更多(约30至50)。

Recently I came across a piece of code wherein I found an interface with only constants. And those constants were accessed in classes using static imports. The constants were more in number (around 30 to 50).

就我个人而言,我认为这不是一个好习惯。这就是为什么它根据Effective Java被称为Constant Interface Antipattern。我没有找到任何合理的理由去进行这种编码。

Personally, I don't think it's a good practice. Thats why its called as Constant Interface Antipattern according to Effective Java. I don't find any good reason to go for this kind of coding.

此外,如果很多类导入的常量很少,则只应使用静态导入。在我们的申请中。

Also, static import should be used ONLY if there are few constants to be imported by many classes in our application.

如果有任何其他充分理由可以选择常量界面,请有人告诉我吗?

Can anyone of you please let me know if there are any other good reasons to go for constants only interface?

推荐答案

当然,在引入枚举之前,如果你需要在许多类之间共享大量常量,那么Constant Interface可能是最实用的方法所以。

Certainly prior to the introduction of enums, if you had a large collection of constants that needed to be shared between a number of classes, a Constant Interface was probably the most pragmatic way to do so.

如果这些常量只用在一个类中,那么其他答案中的注释('避免模式')是非常有效的 - 如果由使用它们的类声明。

If those constants were only used in one class then the comments in other answers ('a pattern to avoid') are quite valid - they would be most useful if declared by the class that uses them.

对于较新版本的Java,我将使用允许设置值的构造函数转向枚举。但是仍然如此,如果这组值仅由一个类使用,那么在该类中而不是单独声明它们是最有意义的。

With newer versions of Java, I'd move towards enums with a constructor that allows value(s) to be set. However it's still the case that if the set of values are only used by a single class, it makes most sense to declare them within that class rather than separately.

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

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