Java的常量文件 [英] Java constants file

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

问题描述

我开发一个Android应用程序,我非常新的Java和Android的。

I'm developing an Android application and I'm very new on Java and Android.

我想创造一些常量在一些活动中使用。我在哪里可以定义这些常量?

I want to create some constants to use in some activities. Where can I define these constants?

感谢。

推荐答案

它被认为在Java中不好的做法,大多数面向对象的语言,定义一个类简单地保持常量。这是更好的在它们与相关联的类中定义的常量。通常有一个。例如,

It's considered bad practice in java, and most OO languages, to define a class simply to hold constants. It's much better to define the constants in a class they are associated with. Usually there is one. e.g.

interface MyComponent {
  /** The default height for a component */
  public static final int DEFAULT_HEIGHT = 5;
  // other stuff
}

如果真的没有感到自由定义一个单独的类。

If there really isn't one feel free to define a separate class.

编辑:这里的关键事情是:

The key things here are:

  1. 请常量容易找到。如果有一个自然的地方,把它们,把它们放在那里(即默认高度组件对象属于组件类)。
  2. 请不要有更高的耦合比你需要。把所有的常量在一个常量级使得高耦合,特别是随后的修饰语往往然后把所有的常量在常量类,无论是否有另一个阶级,他们可以自然地放在
  3. 仅仅因为一个常数使用多个类,这并不意味着它应该是一个常量类。如果一个常数使用'应用'的和使用的应用程序类的类的然后把它在应用程序类。这样,你不增加耦合。
  1. Make the constants easy to find. If there is a 'natural' place to put them, put them there (i.e. the default height for Component objects belong in the Component class).
  2. Don't have higher coupling than you need to. Putting all your constants in one 'Constants' class makes for high coupling, especially as subsequent modifiers tend to then put ALL constants in the Constants class, whether or not there is another class they could naturally be put in.
  3. Just because a constant is used by more than one class that doesn't mean it should be in a 'Constants' class. If a constant is used by 'Application' and classes that use the Application class then put it in the Application class. That way you are not increasing the coupling.

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

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