Search code examples
javaandroidstaticintnaming

Working with constants in Java: How to log the name given to them?


Let's say we have one class that looks like this:

public class UserAction {

    static final int ACTION_USER_WANTS_TO_DO_A = 1001;
    static final int ACTION_USER_WANTS_TO_DO_B = 1002;
    // ...

    // 'sub-grouping'
    static final int[] ALL_ACTIONS_ALLOWED_IN_STATE_X = {
        ACTION_USER_WANTS_TO_DO_A,
        ACTION_USER_WANTS_TO_DO_D,
        ACTION_USER_WANTS_TO_DO_Q,
        // ... 
    }

}

... and another class that looks like this:

public class Model {

    public void onActionableEvent(int action) {

        // check for state mismatch by iterating over sub-groups
        // if (fail) {return;}, if pass:

        Log.i("XXX","processing: " + action); // <----- this is the problem.

        switch (action) {
            case: .ACTION_USER_WANTS_TO_DO_A: {
                //
                break;
            }
            case: .ACTION_USER_WANTS_TO_DO_B: {
                //
                break;
            }
        }
    }

}

I'm having trouble logging the actual name of the actions instead of the raw int... without doing whole bunch of inefficient code -- eg. logging raw Strings in each case block separately, using a Hashmap where refactoring the names will become cumbersome.

My question is: What data structure can be used that will:

1) Allow 'UserActions' to be sub-grouped as they are in the UserAction class -- in a way that the sub-group can be iterated over. (This rules out Enum, for example).

2) Will show the actual name of the action in the Log (.toString(), for example), instead of just showing the actual int value (number)? (seems to rule out int... which is what I'm using).

3) Can be used statically as in the example without having to construct an instance of UserAction.


Solution

  • I'd say that enum is what you need. Something like this:

    enum USER_ACTIONS { ACTION_USER_WANTS_TO_DO_A, ACTION_USER_WANTS_TO_DO_B };

    And trying to answer your 3 questions:

    1) they are groupped in the enum

    2) in the log you'll get processing: ACTION_USER_WANTS_TO_DO_A

    3) yes