定义应用程序中使用的常量的最佳实践 [英] Best practices to define constants used in an app
问题描述
我在 provider 包中有一个ContentProvider,其中声明了JOIN查询:
I have a ContentProvider in a provider package where a JOIN query is declared:
final String ALL_DATA_FOR_AN_ANIMAL = "SELECT " +
"animals._id, "
+ COLUMN_NAME + " AS _name, "
+ COLUMN_CLASSE + " AS _class, "
+ "IFNULL(" + COLUMN_OVERRIDE_INDIVIDU_NUMBER + ", " + COLUMN_INDIVIDU_NUMBER + ")" + " AS _ind_nb, "
+ "FROM " + ANIMALS_TABLE_NAME + " LEFT JOIN " + ANIMALS_OVERRIDE_TABLE_NAME
+ " ON " + COLUMN_NAME + " = " + COLUMN_OVERRIDE_NAME
+ " WHERE animals._id = ?";
在AS中定义的所有sql别名都在ContentResolver中使用(在操作中包)来定义传递给ContentProvider中查询的投影和选择
All the sql aliases defined with AS are used in a ContentResolver (in an operations package) to define projection and selection passed to the query in the ContentProvider
String[] projection = new String[]{"_name", "_class", "_ind_nb", "_in_danger"};
String selection = "_id";
String[] selectionArgs = {selectionArg};
return mCr.query(uri, projection, selection, selectionArgs, sortOrder);
最后,别名用于在视图中显示查询结果包
tv_Name.setText(cursor.getString(cursor.getColumnIndex("_name")));
tv_Class.setText(cursor.getString(cursor.getColumnIndex("_class")));
//...
我认为最好在a内定义别名 Constants 类,而不是使用硬编码的字符串,但是我已经在 ui.utils 包中为ui声明了一些常量。
I think it would be better to define the aliases inside a Constants class instead of using hard-coded Strings, but I already have some constants declared for the ui in a package ui.utils.
最佳做法是什么?为整个应用编写一个 Constants 类专业包还是编写一个 Constants 类更好? (..或通过其他软件包使用这些别名是否表示体系结构不好?)
What are the best practices? Is it better to write one Constants class pro package or to write a single Constants class for the entire app ? (.. or using these aliases through different package is a sign of bad architecture?)
更新
下面是我为gui实现的 Constants 类,该类在软件包 view.utils
Below is the Constants class I implemented for the gui, this class is in the package view.utils
public class Constants {
public static final int ANIMAL_PAGE_POS = 0;
public static final int CARACTERISTICS_PAGE_POS = 1;
//...
}
我会为别名,例如:
public class Constants {
public static final String ALIAS_ID = "_id";
public static final String ALIAS_NAME = "_name";
//...
}
问题是:
- 在不同的软件包之间共享变量(特别是别名)是一个很好的解决方案吗?
- (如果答案为第一个问题是)我是否必须创建多个类似Constants的类,还是在一个Constants类中为所有包定义所有常量的好习惯?
推荐答案
有一件事我忘了说,我定义了一个Contract类,其中定义了所有表。正如@Sourabh所建议的那样,我使用此类定义了JOIN查询所需的常量
One thing I forgot to say it that I defined a class Contract where all tables are defined. As @Sourabh suggested I used this class to define the constants I need for the JOIN query
public static final class JoinEntry implements BaseColumns {
public static final String COLUMN_JOIN_NAME = "_name";
public static final String COLUMN_JOIN_CLASS = "_class";
public static final String COLUMN_JOIN_SUB_CLASS = "_sub_class";
public static final String COLUMN_JOIN_NB_IND = "_ind_nb";
}
这篇关于定义应用程序中使用的常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!