What are enums and why are they useful?

后端 未结 27 1318
一整个雨季
一整个雨季 2020-11-22 07:06

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits

27条回答
  •  情深已故
    2020-11-22 07:24

    Apart from all said by others.. In an older project that I used to work for, a lot of communication between entities(independent applications) was using integers which represented a small set. It was useful to declare the set as enum with static methods to get enum object from value and viceversa. The code looked cleaner, switch case usability and easier writing to logs.

    enum ProtocolType {
        TCP_IP (1, "Transmission Control Protocol"), 
        IP (2, "Internet Protocol"), 
        UDP (3, "User Datagram Protocol");
    
        public int code;
        public String name;
    
        private ProtocolType(int code, String name) {
            this.code = code;
            this.name = name;
        }
    
        public static ProtocolType fromInt(int code) {
        switch(code) {
        case 1:
            return TCP_IP;
        case 2:
            return IP;
        case 3:
            return UDP;
        }
    
        // we had some exception handling for this
        // as the contract for these was between 2 independent applications
        // liable to change between versions (mostly adding new stuff)
        // but keeping it simple here.
        return null;
        }
    }
    

    Create enum object from received values (e.g. 1,2) using ProtocolType.fromInt(2) Write to logs using myEnumObj.name

    Hope this helps.

提交回复
热议问题