I am trying to do something that usually looks in C:
typedef enum { HTTP =80, TELNET=23, SMTP =25, SSH =22, GOPHER=70} TcpPort;
Approach 1
Here is what I have in Java using enum :
public static enum TcpPort{ HTTP(80), TELNET(23), SMTP(25), SSH(22), GOPHER(70); private static final HashMap<Integer,TcpPort> portsByNumber; static{ portsByNumber = new HashMap<Integer,TcpPort>(); for(TcpPort port : TcpPort.values()){ portsByNumber.put(port.getValue(),port); } } private final int value; TcpPort(int value){ this.value = value; } public int getValue(){ return value; } public static TcpPort getForValue(int value){ return portsByNumber.get(value); } }
Approach 1 - Problems
I find that I have to repeat this pattern in different places, but wondered: is there a better way? especially because:
- it seems confusing and less elegant, and
- it also shifts what will compile time to run. "
One of the reasons I use this mapping is because it looks better in switch statements, for example:
switch(tcpPort){ case HTTP: doHttpStuff(); break; case TELNET: doTelnetStuff(); break; .... }
I believe there are advantages to stronger enumerated type safety.
Approach 2 I know I could:
public static class TcpPort{ public static final int HTTP = 80; public static final int TELNET = 23; public static final int SMTP = 25; public static final int SSH = 22; public static final int GOPHER = 70; }
but I feel that enum is still better. Is my approach enum above the way? or is there another way?
source share