简体   繁体   English

简化if else语句

[英]simplify if else statement

I have some functionality dependent on many conditions. 我有一些功能取决于许多条件。 All variables in conditional statements are boolean variables and the code is the following and I don't like it: 条件语句中的所有变量都是布尔变量,代码如下,我不喜欢它:

    if (userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency) {
        if (isOnlyAgencySelected) {
            //do case 1

        } else if (noAgencySelected && isOnlyMarketSelected) {
            //do case 2
        }
    }

Is there a way to make it more understandable and nice? 有没有办法使它更容易理解和更好?

That's about as concise as you're going to get with JavaScript. 这与使用JavaScript一样简洁。 I suppose if you really wanted to, you could create variables to store your binary options: 我想如果您真的想要,可以创建变量来存储二进制选项:

var multiMarketOneSelected = userHasMoreThanOneMarket && isOnlyMarketSelected;
var singleMarketMultiAgency = !userHasMoreThanOneMarket && userHasMoreThanOneAgency;

if (multiMarketOneSelected || singleMarketMultiAgency) {
    if (isOnlyAgencySelected) {
        //do case 1

    } else if (noAgencySelected && isOnlyMarketSelected) {
        //do case 2
    }
}

Though I don't really know if you gain much readability from that. 虽然我真的不知道您是否从中获得了更多的可读性。

Your code seems fine, but if you don't like it you could do something like this (note that the only improvement here is style, if you like it better): 您的代码看起来不错,但是如果您不喜欢它,则可以执行以下操作(请注意,如果您更喜欢它,这里唯一的改进就是样式):

function check(){
    return {
        valid: userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency,
        case: [
           isOnlyAgencySelected,
           noAgencySelected && isOnlyMarketSelected
        ]
    };
}

var conditions = check();
if (conditions.valid) {
    if (conditions.case[0]) {
        //do case 1
    } else if (conditions.case[1]) {
        //do case 2
    }
}

Some things I would try to make the code more readable: 我会尝试使代码更具可读性的一些事情:

  1. Initialise the variables in a way that you don't have to negate them again. 初始化变量的方式不必再次取反。 So !userHasMoreThanOneMarket becomes userHasOneMarket 所以!userHasMoreThanOneMarket成为userHasOneMarket
  2. isOnlyMarketSelected sounds redundant to me. isOnlyMarketSelected对我来说似乎是多余的。 And you are checking it in the outer if-clause and the inner again. 您正在外部的if子句和内部的if子句中进行检查。
  3. You probably have a lot of code above this code snippet to initialise and set all this boolean values. 在此代码段上方,您可能有很多代码可以初始化和设置所有这些布尔值。 Try return; 尝试return; statements after each variable to get rid of if-conditions. 每个变量之后的语句以消除if条件。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM