0

What is better?

if ("a".equals(x) || "b".equals(x)) {
    //do something
}

vs

private static List<String> validAlphabets = ImmutableList.of("a", "b");
if (validAlphabets.contains(x)) {
    //do something
}

The above code sample is in Java, but this applies to any programming language.

Is one approach better than the other?

One other case would be as follows:

if ("a".equals(x)) {
    return "hello a";
}
else if ("b".equals(x)) {
    return "bye b";
}

This can be written as a Map<String,String>

1 Answer 1

2

I would argue for the second approach, for the following reasons:

  1. There's less chance of making a mistake if you need to add or remove items from the list at some point in the future.
  2. Being able to name the variable (validAlphabets in your case) gives you a valuable opportunity to make your code a little more self-documenting.
1
  • 1
    Generally agree with this answer, and upvoted. However, if "a" and "b" already have good names (or are obvious as strings), and the logic is unlikely to change, I'd go with version 1 for simplicity. For example, if they were "http" and "https".
    – user949300
    Sep 4, 2018 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.