Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Values of Fields as Constants in Java

I'm implementing a standard as an object oriented library in Java. Standard includes many messages which passing over network through terminals. Every message is implemented as a single class.

Some of the fields is represented as char types and those fields have one of the values that is defined in the standard. For example,

public class OutgoingMessage {
    private char action;

and action has these values,

'0' - Do not print
'1' - Print
'2' - Print and Forward
'3' - Print and Reply
'F' - Forward
'R' - Reply

Also some of the classes have more than 2 fields like this. Defining those as constants in the class can be messy in these situations.

So I'm trying to implement those values as

public class OutgoingMessage {
    private char action;

    public final class ActionTypes {
        public static final char DO_NOT_PRINT = '0';
        public static final char PRINT = '1';
        ...

And using as below

...
message.setAction(OutgoingMessage.ActionTypes.DO_NOT_PRINT);
...
message.setFooBar(OutgoingMessage.FooBarTypes.FOO_BAR);
...

What do you think? Is there anything wrong with this approach? How would you define these constants in the library?

Thanks a lot

like image 881
xelon Avatar asked Dec 17 '22 11:12

xelon


1 Answers

Use enums in preference to int or char constants:

public enum Action {
    DoNotPrint,
    Print,
    PrintAndForward,
    PrintAndReply,
    Forward,
    Reply
}

public class OutgoingMessage {
     private Action action;

If you need to associate a char with the action, do this:

public enum Action {
    DoNotPrint('0'),
    Print('1'),
    PrintAndForward('2'),
    PrintAndReply('3'),
    Forward('F'),
    Reply('R');

    private static Map<Character, Action> map = new HashMap<Character, Action>() {{
        for (Action action : Action.values()) {
            put(action.getChar(), action);
        }
    }};

    private final char c;

    private Action(char c) {
        this.c = c;
    }

    public char getChar() {
        return c;
    }

    public static Action parse(char c) {
        if (!MapHolder.map.containsKey(c))
            throw new IllegalArgumentException("Invalid char: " + c);
        return MapHolder.map.get(c);
    }
}

Here's how you can use the parse method:

public static void main(String[] args) {
    System.out.println(Action.parse('2')); // "PrintAndForward"
    System.out.println(Action.parse('x')); // throws IllegalArgumentException
}
like image 79
Bohemian Avatar answered Jan 01 '23 17:01

Bohemian