I'm trying to do something that would normally look like this 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 am having to repeat this pattern in various places, but was wondering: is there a better way? particularly because:
- this seems convoluted and less elegant, and
- it also shifts something that would be compile time to run time".
One of the reasons I use this mapping, is because it looks better in switch statements, e.g.:
switch(tcpPort){
case HTTP:
doHttpStuff();
break;
case TELNET:
doTelnetStuff();
break;
....
}
I suppose there are also benefits of stronger type safety with enums.
Approach 2 I am aware I could do:
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 my feeling is that enum
s are still better. Is my enum
approach above the way to go? or is there another way?