开发者

What's a more stylistically elegant way to assess a large number of Java string comparison conditions?

I have written the following string comparison operation for a feature in my app.

But I hate the way this looks and how unwieldy it is.

String foo = "abc";

if(!foo.startsWith("ba") && 
    !foo.equals("cab") && 
    !foo.equals("bca") && 
    !foo.equals("bbc") && 
    !foo.equals("ccb") && 
    !foo.equals("cc开发者_JAVA技巧a"))
{
    // do something
}

Is there a more elegant and perhaps more maintainable way to write something like this?


You can use a regular expression.

private static final Pattern P = Pattern.compile(
                                 "(ba.*|cab|bca|bbc|ccb|cca)");

String foo = "abc";
if (!P.matcher(foo).matches())


If you only have this condition once in your code, I would let it like this. If you have it several times, initialize a constant set:

private static final Set<String> STRINGS_TO_AVOID = 
    Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("cab", "bca", "bbc", "ccb", "cca")));

...

if (!foo.startsWith("ba") && !STRINGS_TO_AVOID.contains(foo)) {
    ...
}


Regex (ideally) or if/else block. Here's a gentle introduction to Java regular expressions:

http://www.javamex.com/tutorials/regular_expressions/


With your example, you could use a HashSet to put all the Strings you want to compare.

Then you could simply type

 if (!foo.startsWith("ba") && !mySet.contains(foo)) { 
    //doSomething
 }
  • Edit : Dang... i was to late... someone else beat me. ;-)


One could argue that something like the following is more "elegant" than your original code.

if (!foo.matches("^ba.*|^cab$|^bca$|^bbc$|^ccb$|^cca$")) {
  // do something
}

I prefer the original since it is simplest, uses natural language that anyone can understand and therefore it is more maintainable...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜