【问题标题】:Avoid multiple if else避免多个 if else
【发布时间】:2016-06-17 15:22:46
【问题描述】:

我有以下场景,

一个 String arr[] 作为输入,可以有整数值,null 或空字符串。 (例如){"230",null,"6",""}

现在,

1. 如果 arr 的前两个条目中存在 null 或空字符串,则这是一个无效的场景,不打印任何内容。

2.如果 arr 的最后两个条目中存在 null 或空,并且前两个条目不为 null 且不为空,则打印前两个条目。

(例如)如果 arr[] 是 {"2","77",null,"5"} 输出将是 2,77

3. 如果 arr[] 中没有条目既不为空也不为空,则检查所有条目是否为数字。如果不打印什么。

现在我的代码是这样的,

simple validation()
{
    onlyFirstTwoNotNullOrNotEmpty = false;

    if(//Check if first two params are null)
    {
        //"print nothing" and return
    }
    else if(check if third **or** fourth param is null)
    {
        onlyFirstTwoNotNullOrNotEmpty = true; // setting a boolean 
    }

    //Proceed to check empty string
    if(//Check if first two params are empty)
    {
        "print nothing" and return
    }
    else if(!onlyFirstTwoNotNullOrNotEmpty) //checking if null 
    {
        if(check if third **or** fourth param is empty)
        {
            onlyFirstTwoNotNullOrNotEmpty = true; // setting a boolean 
        }
    }

    //if all values are not null and not empty      
    //onlyFirstTwoNotNullOrNotEmpty  will be still false

    String result;

    if(onlyFirstTwoNotNullOrNotEmpty )
    {
        result = checkIfNumeric(0,1); // only first two entries
    }
    else
    {
        result = checkIfNumeric(0,arr[arr.length-1]); // for all entries
    }

    if(!result.equals("success"))
    {
        return and print nothing
    }

    if(onlyFirstTwoNotNullOrNotEmpty)
    {
        print only first two and return;
    }
    print all entries and return;
}

如何使用更少的 if 和 else 循环更好地优化此代码?通过 lambda 表达式有什么可能吗?

我不想使用第三方 API 对字符串进行 null 或 Empty 检查。

【问题讨论】:

  • 我会首先摆脱布尔值并将当它们为真时您采取的动作移动到您设置它们的块中。但这是一个非常不自然的问题,所以如果解决方案看起来也有点不自然,您不必太担心。
  • @AndrewL 对于像if(//Check if first two param are empty){ "print nothing" and return 这样的伪代码,这个问题对于代码审查来说是非常偏离主题的。
  • 我没有看到这一点,当我阅读“如何更好地优化此代码”时,我认为他们已经完成了代码。我的错误@200_success
  • 如果缩进正确,代码会更容易阅读。

标签: java if-statement optimization


【解决方案1】:

你的代码比它需要的复杂得多:

如果代码在它自己的方法中,你可以不使用else 子句,就像你的代码看起来那样。

在这里,用 cmets:

private static void simpleValidation(String[] arr) {
    // Undefined Rule: If bad input, print nothing
    if (arr.length != 4)
        return;

    // 1: If a null or empty string present in first two entries of arr, it is a invalid scenario print nothing
    if (isNullOrEmpty(arr[0]) || isNullOrEmpty(arr[1]))
        return;

    // 2: If a null or empty is present in last two entries of arr, and first two entries are not null and not empty print first two entries.
    if (isNullOrEmpty(arr[2]) || isNullOrEmpty(arr[3])) {
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        return;
    }

    // 3: If no entry in arr[] is neither null nor empty check if all entries are numeric. If not print nothing.
    if (! isNumeric(arr[0]) || ! isNumeric(arr[1]) || ! isNumeric(arr[2]) || ! isNumeric(arr[3]))
        return;

    // Undefined Rule: Print all values
    System.out.println(arr[0]);
    System.out.println(arr[1]);
    System.out.println(arr[2]);
    System.out.println(arr[3]);
}
private static boolean isNullOrEmpty(String value) {
    return (value == null || value.isEmpty());
}
private static boolean isNumeric(String value) {
    return value.matches("\\d+");
}

如果您希望它带有 else 子句且没有 return 语句,例如因为后面有更多代码,就这么简单(使用相同的两个辅助方法):

private static void simpleValidation(String[] arr) {
    if (arr.length == 4 && ! isNullOrEmpty(arr[0]) && ! isNullOrEmpty(arr[1]))
        if (isNullOrEmpty(arr[2]) || isNullOrEmpty(arr[3]))
            System.out.printf("%s%n%s%n", arr[0], arr[1]);
        else if (isNumeric(arr[0]) && isNumeric(arr[1]) && isNumeric(arr[2]) && isNumeric(arr[3]))
            System.out.printf("%s%n%s%n%s%n%s%n", arr[0], arr[1], arr[2], arr[3]);
}

【讨论】:

    【解决方案2】:

    也许您可以为此使用 switch 语句。循环遍历数组的值并使用 switch 语句而不是 if-else。

    https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2019-03-27
      相关资源
      最近更新 更多