在java中如何存储像文件路径这样的全局变量? [英] Where to store global variables like file paths in java?

查看:363
本文介绍了在java中如何存储像文件路径这样的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用了一些图标。我应该在哪里存储包含这些图标的目录的路径?

图标在不同的类中使用,因此将它们存储在其中一个类中是没有意义的。

我读过全局变量是邪恶的,但是使用仅包含一个类的类(例如 Commons )是可以接受的 public static final 字段来存储这个数据之王?

解决方案

全局常量



其他人声明,全局常量与全局变量不具有相同的负面含义。由于不受控制的修改,全局变量使程序难以调试和维护。全局常量( public static final )不会产生同样的问题。然而,面向对象是关于绑定代码接近其数据以增强可理解性和可维护性。您仍然需要在将全局配置值存储在全局类中,并将数据保存到将要使用它的代码之间找到适当的平衡。



在这里也值得提醒,因为编译器可能内联一些常量,所以如果你改变一个常量值,你可能不得不重新编译和重新部署,而不仅仅是包含常量的类。


外部化值



您还询问了专业应用的功能。这些应用程序使用这些类型的值(如文件路径)可以在外部进行配置,这种情况并不少见。它取决于值的可能变化程度(即应用程序移动的可能性或您的代码在另一个应用程序中的使用程度),以及使用新值重新编译和重新部署代码有多么方便或容易。如果您确实选择将某些值设置为可外部配置,那么您仍可能需要为代码中的这些项目编码默认值。



以下是一些将这些值进行外部化的方法,一些链接让你开始。这当然不是一个详尽的清单:




In my application I use some icons. Where should I store the path of the directory containing those icons ?

The icons are used in different classes so it doesn't really make sense to store them in one of those classes in particular.

I read that global variables are evil, but is it acceptable to use a class (eg Commons) containing only public static final fields to store this king of data ? What solution is used in professional applications ?

解决方案

Global Constants

As others state, global constants don't have the same negative connotation as global variables. Global variables make a program difficult to debug and maintain because of uncontrolled modifications. Global constants (public static final) don't create the same problem

Nevertheless, object-orientation is about binding code close to its data to enhance understandability and maintainability. You still have to find the right balance between storing global configuration values in a global class vs keeping data close to the code that will use it.

It is probably also worth reminding here that, because the compiler may inline some constants, if you change a constant value, you may have to recompile and redeploy more than just the class that contains the constants.

Externalizing Values

You also asked about what professional apps do. Its not uncommon for those apps to make these types of values, like files paths, externally configurable. It depends on how likely the value is to change (i.e. how likely your app will move or your code will be used in another app) and how convenient or easy it is to recompile and redeploy the code with new values. If you do choose to make some values externally configurable, you still may want to encode default values for those items in the code.

Here are some ways to externalize those values and some links to get you started. This is of course not an exhaustive list:

这篇关于在java中如何存储像文件路径这样的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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