I've often run through a validation pattern where, to be valid, some variables must contain one of a prefixed number of values.
PSEUDO CODE:
IF x == CONSTANT_1 || X == CONSTANT_2 || ... || x == CONSTANT_N
THEN X is valid
In order to avoid the chain of OR terms, I created a static final unmodifiable set, which contains all the constants:
public final static String CONSTANT_1 = *value* ;
public final static String CONSTANT_2 = *value* ;
...
public final static String CONSTANT_N = *value* ;
public final static Set SET_OF_CONSTANTS = Collections.unmodifiableSet(new HashSet(){
private static final long serialVersionUID = 1L;
{
add(CONSTANT_1);
add(CONSTANT_2);
...
add(CONSTANT_3);
}
});
And I perform the check in the following way:
if(!SET_OF_CONSTANTS.contains(x)){
//X NOT VALID
}
I'd like to know if this is a good programming practice, if there are any alternatives, and if it's true that using a Hash Table query (O(1) in theory) instead of the OR terms-chain improves performance and maybe also code-readability.