HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Using Enum to Handle String literals

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
literalshandleenumusingstring

Problem

I have a java component that was using a lot of string literals that I need to make comparisons on and return booleans based on these comparisons.

In order to make the code more robust I externalized these strings first as class constants, then after other classes started to use these constants I had to separate them to decrease the dependency between the classes.

Knowing that the best practice is not to use variable-classes dedicated for string for many reasons, and since I am using Java 6, I decided to go for enums. below is the implementation that I had in mind

public enum SecurityClassification {
    SENSITIVE("Sensitive"), HIGHLY_SENSITIVE("Highly Sensitive"), PUBLIC("Public"), INTERNAL("Internal");

    private String value;

    private SecurityClassification(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public boolean hasValue(String param) {
        return value.equalsIgnoreCase(param);
    }

    public static SecurityClassification enumForValue(String param){
        for (SecurityClassification securityClassification : SecurityClassification.values()) {
            if(securityClassification.getValue().equals(param)){
                return securityClassification;
            }
        }
        return null;
    }
}


I was wondering specifically about the enumForValue method, is this an optimal solution? is there any other better way?

Solution

It looks fine overall, but...

A few pointers

-
You should make private String value final too though, to clearly indicate that they cannot be modified after instantiation.

-
One thing to note for values() is that it always returns a new array, so for that reason, sometimes it may be recommended to also construct a lookup Map to avoid the extra arrays creation.

-
Also, is it really OK to just return null if an invalid security classification is specified here? Depending on your implementation, you may want to consider whether you should throw an IllegalArgumentException here to have a slightly better modelling of such cases.

-
How is hasValue() used? In fact, can it be used in enumForValue() for a case-insensitive comparison?

-
Finally, enumForValue() may seem like a mouthful, you can consider a shorter name like of(). The other thing to consider is that you don't really need to express that it's an enum this method is returning.

Context

StackExchange Code Review Q#122212, answer score: 3

Revisions (0)

No revisions yet.