更清洁的IF声明 [英] A Cleaner IF Statement
问题描述
在Java中,当你有很多术语时,以下陈述看起来非常混乱:
In Java, The following statement just looks very messy when you have a lot of terms:
if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... )
//Do something
是否有更简洁的方法来执行相同的操作,我希望我的代码尽可能可读。
Is there a cleaner way of performing the same action, I would like my code to be as readable as possible.
注意:x,y和z只是任何长度的任何字符串的占位符。这里有20个可变长度的字符串术语,如果条件每个都是OR在一起
NOTE: x, y and z are just placeholders for any string of any length. There could be 20 string terms here of variable length in if condition each being OR'd together
谢谢
推荐答案
Set<String> stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
if(stuff.contains(a)) {
//stuff
}
如果这是一个紧密循环,你可以使用一个静态Set。
If this is a tight loop you can use a static Set.
static Set<String> stuff;
static {
stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
}
//Somewhere else in the cosmos
if(stuff.contains(a)) {
//stuff
}
如果你想更加确定在你不看的时候没有任何东西被修改。
And if you want to be extra sure nothing is getting modified while you're not looking.
Set<String> test = Collections.unmodifiableSet(new HashSet<String>() {
{
add("x");
add("y");
add("z");
}
});
如果您只是想在一些硬编码条件下得到一些逻辑,那么其中一个切换或if语句与换行解决方案可能会更好。但是如果你有很多条件,那么将配置与逻辑分开可能会很好。
If you just want to get some logic in there for a handful of hard coded conditions then one of the switch or if statement with newlines solutions might be better. But if you have a lot of conditions then it might be good to separate your configuration from logic.
这篇关于更清洁的IF声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!