永远不要使用公共嵌套枚举?

AEW*_*AEW 14 java enums coding-style nested-class inner-classes

我最近遇到了一个编码标准声称你永远不应该使用Java中的公共内部枚举/类.这是我第一次遇到这个惯例,并且未能找到令人满意的解释原因.

我理解为什么应该避免使用公共内部类,但是为什么你永远不会使用公共嵌套枚举?或者,为什么这是一个糟糕的惯例?

Viv*_*ath 13

免责声明: 以下不是硬性规定.这些只是我的意见和个人喜好.我个人发现它使我的代码更容易阅读,更容易维护.

首先是一个问题.你在哪里遇到这个建议?他们提供了任何理由吗?

根据我的经验,我通常使用私有嵌套枚举来增强代码的可读性和可维护性.当您执行与其他系统的集成并且必须发送特定字符串或数字时,这尤其起作用.我发现使用枚举可以使事情更容易阅读和维护.在这种特定情况下,枚举所传达的信息在范围内受限于班级(即,在课堂之外没有任何意义,没有其他人需要它).

我想不出一个明确的理由说明为什么公共内部枚举是一种不好的做法.但这是我不(通常)使用它们的原因:

  • 如果枚举是公共​​的,它实质上意味着它在更大的范围内传递信息(即,在其父类的范围之外有意义,因此它可能意味着其他东西正在使用它).如果是这种情况,那么将它作为一个独立的枚举可能更有意义.
  • 我发现 ThirdPartyResponseCodes.Success眼睛更容易而不是ThirdPartyIntegrationInterface.ThirdPartyResponseCodes.Success.没有理由为什么你不能恰当地命名枚举来提供上下文,从而使它成为一个独立的枚举.
  • I would imagine that the same reasons for not using public inner classes also apply to public inner enums. First of all, if you have an inner class, it may mean that your outer class might benefit from refactoring. Perhaps your outer class is trying to do too much? On the flip side though, there is the benefit of encapsulation and limiting scope, especially if you can make the argument that the inner class only makes sense in the context of the outer class (which should go without saying if it is private). If it is a public inner class, then that probably means that its scope extends past the outer class and thus it would need to be pulled out.
  • 如果你确实需要使用公共嵌套枚举,那么你应该准确记录你需要它的原因(我还没有找到理由这样做)以及为什么最好将它作为公共嵌套枚举而不是公共独立枚举.