What are enums and why are they useful?

后端 未结 27 1319
一整个雨季
一整个雨季 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:42

    Enum? Why should it be used? I think it's more understood when you will use it. I have the same experience.

    Say you have a create, delete, edit and read database operation.

    Now if you create an enum as an operation:

    public enum operation {
        create("1")
        delete("2")
        edit("3")
        read("4")
    
        // You may have is methods here
        public boolean isCreate() {
            return this.equals(create);
        }
        // More methods like the above can be written
    
    }
    

    Now, you may declare something like:

    private operation currentOperation;
    
    // And assign the value for it 
    currentOperation = operation.create
    

    So you can use it in many ways. It's always good to have enum for specific things as the database operation in the above example can be controlled by checking the currentOperation. Perhaps one can say this can be accomplished with variables and integer values too. But I believe Enum is a safer and a programmer's way.

    Another thing: I think every programmer loves boolean, don't we? Because it can store only two values, two specific values. So Enum can be thought of as having the same type of facilities where a user will define how many and what type of value it will store, just in a slightly different way. :)

提交回复
热议问题