Use enum class to avoid String errors.

Have you got a Logic error in String before specially in Upperletter or Lowerletter?

Here is the solution, but first let’s get into this problem.

assume you have a guitar market or any kind of market and the guiter class like that

And you have a lot of guitar models and types, so when I search for a special kind I want as a customer

When I search maybe I write small letter or a capital one so the search will find nothing as the types of guitar marked as a String value.

So What is the Solution?
The solution is using the enum class.

what is the enum class ?

An enum is a special “class” that represents a group of constants (unchangeable variables, like final variables).

How to create an enum class?
When you create a class you will choose the enum kind like this.

You will save constant values in the enum class like this

public enum Type {
    ElECTRIC, ACOUSTIC;

    public String toString(){
        switch(this){
            case ElECTRIC : return "Electric";
            case ACOUSTIC : return "Acoustic";


            default :
                throw new AssertionError(this.name());
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

You can change the value of constant in toString method or let it.

And when you search for it, you will write (enumClassname.value)

Then you won’t face any logic error in your project

So look again at guitar class after changing every string type to enum class.

Note: If you are mobile developer or web developer the enum class like a spinner and you select you want from it

Resources:
Head first object-oriented analysis and design Book

See you Soon ^_^

原文链接:Use enum class to avoid String errors.

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容