oop - Defining Values of Fields as Constants in Java -
i'm implementing standard object oriented library in java. standard includes many messages passing on network through terminals. every message implemented single class.
some of fields represented char types , fields have 1 of values defined in standard. example,
public class outgoingmessage { private char action;
and action has these values,
'0' - not print '1' - print '2' - print , forward '3' - print , reply 'f' - forward 'r' - reply
also of classes have more 2 fields this. defining constants in class can messy in these situations.
so i'm trying implement 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 below
... message.setaction(outgoingmessage.actiontypes.do_not_print); ... message.setfoobar(outgoingmessage.foobartypes.foo_bar); ...
what think? there wrong approach? how define these constants in library?
thanks lot
use enums in preference int
or char
constants:
public enum action { donotprint, print, printandforward, printandreply, forward, reply } public class outgoingmessage { private action action;
if need associate char
action, 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>() {{ (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 can use parse method:
public static void main(string[] args) { system.out.println(action.parse('2')); // "printandforward" system.out.println(action.parse('x')); // throws illegalargumentexception }
Comments
Post a Comment