DEV Community

Cover image for Use enum class to avoid String errors.
Hamza Gamal
Hamza Gamal

Posted on

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

Image description

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.

Image description

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.

Image description

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 ^_^

Top comments (0)