包含多个比较的更清晰的if语句 [英] A cleaner if statement with multiple comparisons

查看:67
本文介绍了包含多个比较的更清晰的if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您使用很多术语时,以下语句看起来非常混乱:

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个可变长度的字符串术语

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");
        }
    });

如果您只是想为一些硬编码条件提供一些逻辑,那么使用switch或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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆