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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With