【发布时间】:2021-04-06 15:27:22
【问题描述】:
我必须实现康威的生命游戏。一切正常,并且给定的测试正在通过。我唯一的问题是,在我的文件上运行 PMD 规则时,这种方法会产生复杂性错误。我知道有很多 if 语句是造成这种情况的原因,但是在尝试将它们压缩成更小的组时,我不小心破坏了我的代码。
它是这样说的:
The method 'getNeighbourCount(int, int)' has a cyclomatic complexity of 21.
The method 'getNeighbourCount(int, int)' has an NPath complexity of 20736, current threshold is 200
优化此方法的最佳选择是什么?
public Integer getNeighbourCount(int x, int y) {
// x = column (20), y = row (15)
int countNeigbours = 0;
if (x != 0 && y != 0 && isAlive(x - 1,y - 1)) {
countNeigbours++;
}
if (x != 0 && isAlive(x - 1, y)) {
countNeigbours++;
}
if (x != 0 && y != rows - 1 && isAlive(x - 1,y + 1)) {
countNeigbours++;
}
if (y != 0 && isAlive(x,y - 1)) {
countNeigbours++;
}
// check self
if (y != rows - 1 && isAlive(x,y + 1)) {
countNeigbours++;
}
if (x != columns - 1 && y != 0 && isAlive(x + 1,y - 1)) {
countNeigbours++;
}
if (x != columns - 1 && isAlive(x + 1, y)) {
countNeigbours++;
}
if (x != columns - 1 && y != rows - 1 && isAlive(x + 1,y + 1)) {
countNeigbours++;
}
return countNeigbours;
}
isAlive 返回布尔值,如果单元格被占用(真)或不被占用(假)。
【问题讨论】:
标签: java optimization cyclomatic-complexity