내 코드는 매우 복잡합니다. 어떻게 줄일 수 있습니까?
Nov 24 2020
'아톰'이라는 간단한 게임을 코딩하려고합니다. 정말 잘 작동하지만 약간의 문제가 있습니다. VisualStudio는 아래 첫 번째 코드의 복잡성이 10이고 두 번째 코드의 복잡성이 13이라고 말합니다. 복잡성을 어떻게 줄일 수 있습니까? 미리 감사드립니다 :)
checkForWin(){
let winner = true;
for(let i = 0; i < this.fieldSize; i++){
for(let j = 0; j < this.fieldSize; j++){
if(this.htmlBoard[j][i].classList.contains("atom")){
if(this.htmlBoard[j][i].classList.contains("suspectAtom")){
this.setField(j, i, "correct");
}
else{
this.setField(j, i, "wrong");
winner = false
}
}
else if(this.htmlBoard[j][i].classList.contains("suspectAtom")){
if(!this.htmlBoard[j][i].classList.contains("atom")){
this.setField(j, i, "wrong");
winner = false
}
}
}
}
return winner;
},
setBorder() {
for (let y = 0; y < this.fieldSize; y++) {
for (let x = 0; x < this.fieldSize; x++) {
if (
x == y ||
(x === 0 && y === this.fieldSize - 1) ||
(y === 0 && x === this.fieldSize - 1)
) {
continue;
}
if (
y == 0 ||
x == 0 ||
y == this.fieldSize - 1 ||
x == this.fieldSize - 1
) {
this.board[x][y] = "borderField";
this.htmlBoard[x][y].classList.add("borderField");
}
}
}
},
답변
General_Twyckenham Nov 24 2020 at 18:48
단순화하는 한 가지 방법은 조건부에서 반복을 분리하는 것입니다. Visual Studio Code의 자동 리팩토링을 사용하면 함수를 매우 쉽게 추출 checkForWin
할 수 있으므로 함수가 다음과 같이 보일 수 있습니다.
checkForWin() {
let winner = true;
for (let i = 0; i < this.fieldSize; i++) {
for (let j = 0; j < this.fieldSize; j++) {
winner = this.checkForWinningCondition(j, i, winner);
}
}
return winner;
}
이제 순환 복잡도가 4입니다. (추출 된 함수는 8이됩니다.)
취할 수있는 또 다른 단계는 이러한 조건문 중 일부를 풀고 추가 코드를 제거 할 수 있는지 확인하는 것입니다. 이 경우, 라인 if(!this.htmlBoard[j][i].classList.contains("atom")){
은 이미 초기 if
명령문에 의해 처리 되었기 때문에 관련성이 없습니다 . 이것을 제거하면 추출 된 함수가 7로 낮아집니다.
두 번째 함수에서 동일한 리팩토링 접근 방식을 수행하면 유사한 결과가 생성되며 총 복잡성 점수가 낮아집니다.