下面这个方法用来打印一个整数数组的平均值:static double average(int[] values) {
    if (values == null)
        throw new IllegalArgumentException();
    else
        if (values.length == 0)
            throw new IllegalArgumentException();
        else {
            double sum = 0.0;
            for (int i = 0; i < values.length; i++)
                sum += values[i];
    return sum / values.length;
        }
}其中使用了两个if else来确保数组不为null并且长度不为0,可是书上说:
"this code works but the logic of the method is almost completely lost"
并且提供了另一种判断方法:if (values == null || values.length == 0)
    throw new IllegalArgumentException();不理解为什么书上说第一种方法没有逻辑,私以为第一种方法结构层次更清晰,更容易理解,可以谈谈你的看法么?谢谢!

解决方案 »

  1.   

    两个判断要做的操作都是一样的,完全可以而且应该放到同一个if里
    你这样多做判断完全是多余的行为。
    实际编程中如果按lz的第一种方法写,CodeReview时会被骂死
      

  2.   

    我的理解是(values == null)和(values.length == 0)都是判断合法性,并且抛出相同异常new IllegalArgumentException()
    应该属于同类的逻辑判断如果是两个判断分开就是代码冗余
    如果把其中一个归入另外的逻辑判断,显然更不合适
      

  3.   


    感觉把(values.length == 0)归入(values == null)还是蛮有道理的,因为判断(values.length == 0)的前提就是要(values == null)不成立
      

  4.   

    这么多 if...else 看着头就晕,就算分开来写,也不用这么写吧public class Test {    public static double average(int[] values) {        if(values == null) {
                throw new IllegalArgumentException("空指针");
            }        if(values.length == 0) {
                throw new IllegalArgumentException("空数组");
            }        double sum = 0.0;
            for (int i = 0; i < values.length; i++) {
                sum += values[i];
            }        return sum / values.length;
        }
    }
      

  5.   

    我想這句
    "this code works but the logic of the method is almost completely lost"
    的意思是:
    不空和長度不為0都是參數所要求的條件,故放在一起是一個自然而合乎邏輯的做法,而將不必要劃分的整體分開the logic of the method is almost completely lost,就是讀代碼時會有麻煩吧,當然這個例子看不到麻煩的地方,看上去煩瑣罷了
      

  6.   


    if (values == null || values.length == 0)
        throw new IllegalArgumentException();
    当然是这个更容易理解了,不管出现那种问题,都抛异常。简单明了
      

  7.   

    if
    else if
    else
    if
    else if
         else