从不使用公共嵌套枚举?
我最近遇到一个编码标准,声称您不应该永远在 Java 中使用公共内部枚举/类。这是我第一次遇到这个约定,并且无法找到令人满意的解释。
我明白为什么应该避免公共内部类,但是出于什么原因你永远不会使用公共嵌套枚举?或者,为什么这是一个不好遵循的惯例?
I recently came across a coding standard claiming that you should never use public inner enums/classes in Java. This is the first time I've encountered this convention, and haven't been able to find a satisfactory explaniation as to why.
I understand why public inner classes should be avoided, but for what reasons would you never use public nested enums? Or, why is this a bad convention to follow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
免责声明: 以下内容并非硬性规定。这些只是我的意见和个人喜好。我个人发现它使我的代码更易于阅读和维护。
首先是一个问题。您从哪里看到这个建议?他们有提供任何理由吗?
根据我的经验,我通常使用私有嵌套枚举来增强代码的可读性和可维护性。当您执行与另一个系统的集成并且必须发送特定的字符串或数字时,这一点尤其重要。我发现使用枚举使事情更容易阅读和维护。在这种特定情况下,枚举传达的信息仅限于类的范围(即,它在类之外没有任何意义,并且其他人不应该需要它)。
我想不出一个明确的理由来说明为什么公共内部枚举是一种不好的做法。但以下是我(通常)不使用它们的原因:
ThirdPartyResponseCodes.Success
比ThirdPartyIntegrationInterface.ThirdPartyResponseCodes.Success
更直观。您没有理由不能适当地命名枚举以提供上下文,从而使其成为独立的枚举。Disclaimer: The following are not hard and fast rules. These are just my opinions and personal preferences. I personally find that it makes my code easier to read and easier to maintain.
First a question. Where did you come across this advice? Did they provide any rationale?
In my experience, I've normally used private nested enums to enhance readability and maintainability of my code. This especially comes into play when you're performing an integration with another system and you have to send in specific strings or numbers. I find that using an enum makes things easier to read and maintain. In this specific case, the information conveyed by the enum is limited in scope to the class (i.e., it makes no sense outside the class and no one else should need it).
I can't think of a definitive reason that says why public inner enums are a bad practice. But here are reasons why I don't (normally) use them:
ThirdPartyResponseCodes.Success
easier on the eyes rather thanThirdPartyIntegrationInterface.ThirdPartyResponseCodes.Success
. There is no reason why you cannot name the enum appropriately to provide context and thus make it a standalone enum.原因大概是它使得这些枚举很难在声明它们的类之外使用,因为您必须使用封闭类的名称来限定它们。当然,对于任何公共内部类也是如此。我不确定我是否同意这一点——当然不是一条硬性规定。
The reason is presumably that it makes those enums difficult to use outside of the class in which they are declared, since you have to qualify them with the enclosing class' name. Same is true for any public inner class, of course. And not sure I'd agree with it -- certainly not as a hard-and-fast rule.
如果该编码标准没有包含解释,您必须询问编写该编码标准的人。不过,你的这个说法有点令人困惑:
为什么你认为应该避免公共内部类?为什么这个原因不适用于枚举?
You'll have to ask the person who wrote that coding standard, if it did not contain an explanation. However, this statement of yours is somewhat confusing:
Why do you think public inner classes should be avoided? And why would that reason not apply to enums?