-2

更新:

我有这样的代码:

class Sample 
{
    public boolean isALive(boolean isLive, int num) 
   {
       return isLive ? num == 3 : num == 2 || num == 3;
   } 
}

在测试中,它会是这样的,

assertTrue(x.isAlive(true,1);各种组合

甚至不使用三元运算符,我想以更简单的方式返回相同的结果。

有没有办法做到这一点?

解决方案:返回 num == 3 || (isLive && 数字 == 2); //- 解决方案。

4

1 回答 1

0

编程不是单行的。这是关于可读性。首先我会写一个测试:

import static org.assertj.core.api.Assertions.assertThat;
import org.junit.runner.RunWith;
import com.googlecode.zohhak.api.TestWith;
import com.googlecode.zohhak.api.runners.ZohhakRunner;

@RunWith(ZohhakRunner.class)
public class SampleTest {

    Sample sample = new Sample();

    @TestWith({
        "true,  3,      true",
        "true,  2,      false",
        "false, 3,      true",
        "false, 2,      true",
        "false, 1,      false"
    })
    public void should_xxx(boolean isLive, int num, boolean expectedResult) {

        boolean actualResult = sample.isALive(isLive, num);         
        assertThat(actualResult).isEqualTo(expectedResult);
    }
}

然后我会写:

import static org.apache.commons.lang3.ArrayUtils.contains;

public class Sample {

    public boolean isALive(boolean isLive, int num) {

        int[] liveValues = {3};
        int[] deadValues = {2, 3};

        int[] validValues = isLive ? liveValues : deadValues;
        return contains(validValues, num);
    }
}
于 2013-09-23T18:58:16.557 回答