OLee Csobert OLee Csobert - 1 year ago 80
Java Question

Best practices to define constants used in an app

I have a ContentProvider in a provider package where a JOIN query is declared:

"animals._id, "
+ COLUMN_NAME + " AS _name, "
+ COLUMN_CLASSE + " AS _class, "
+ " WHERE animals._id = ?";

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);

Finally the aliases are used to display the result of the query in the view package


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.

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?)


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;

I would do the same for the aliases, something like:

public class Constants {
public static final String ALIAS_ID = "_id";
public static final String ALIAS_NAME = "_name";

The questions are:

  • is it a good solution to share variables (specifically aliases) across different packages?

  • (if answer to first question is yes) do I have to create multiple Constants-like class or is it a good practices to define all constants for all package inside a single Constants class?

Answer Source

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download