Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum (or int constants) vs c enum

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:

  1. this seems convoluted and less elegant, and
  2. 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 enums are still better. Is my enum approach above the way to go? or is there another way?

like image 254
xirt Avatar asked Apr 29 '15 13:04

xirt


1 Answers

My feeling is that in purposes only for switch statement enum is superfluous in your case, and it is better simply using final static int constants. For instance of memory economy.

Also, Joshua Bloch in his Effective Java recommends using enums instead of int constants in his Item 30: Use enums instead of int constants. But IMHO it is correct way of enum using for more complicated cases then just replacing c #define construction.

UPDATE: as author mentioned in his comment to this my answer, he is wondering is use if enum is better then int constants in general. In this case such question becomes duplicate (see Java: Enum vs. Int), and my answer will: in general enums are better, and why - look at Joshua Bloch's Item 30, as I mentioned before.

like image 76
Andremoniy Avatar answered Oct 28 '22 18:10

Andremoniy