本文介绍了为什么不建议将常量存储在单独的类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我(并且我在其他地方也看到过此声明),建议不要将常量存储在Java的单独类中,以便在其他类中使用它们。但是我还没有看到为什么会这样。我不应该将它们存储在自己的接口/类中的原因是什么?






我是从C到Java的,在C语言中我只会生成 .h 文件,其中用 #define

解决方案

出于风格原因,专用文件中的常量不可用。拥有专门用于常量的类可以鼓励开发人员向逐渐膨胀而不受控制的文件中添加越来越多的无关( undocumented?)常量。




It's been told me (and I have seen this statement in a few other places) that it's not recommended to store your constants in a separate class in Java, in order to use them in the other classes. But I haven't seen anywhere WHY is it so. What is the reason I should not store them in their own interface/class?


I came from C to Java and in C i would just make a .h file where i defined constants with #define

解决方案

Constants in a dedicated file are frowned upon for stylistic reasons. Having a class dedicated to constants can encourage developers to add increasing numbers of unrelated (undocumented?) constants to a file that slowly bloats out of control.

By contrast, having constants associated with the classes they are related to is a more scalable and readable design.

这篇关于为什么不建议将常量存储在单独的类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:04