이번 과제는 클린 코드에 대해 더 알아본 후 아래 코드를 고쳐보는 것이다.
결과는 당연히 문제없이 출력이 된다. 하지만 강의에서 배운 클린코드와는 거리가 멀다!
클래스나 함수로 분리하기 전, 변수명부터 고치기로 했다. 척 보아도 의도를 알 수 있도록
a → inputNum
b → diceValue
r1 → count1
로 바꾸기로 했다.
그 후, 주사위의 눈을 나타내는 diceValue의 타입을 int로 변경하려고 한다. if 문에서 조건을
diceValue>=0 && diceValue<1
이런 범위로 작성하는 것은 직관적이지도 못할 뿐더러, 불필요가 연산자가 더 들어가 비효율적일 것 같았다.
int inputNum = scanner.nextInt();
int count1=0, count2=0, count3=0, count4=0, count5=0, count6=0;
for(int i = 0; i<inputNum;i++){
int diceValue = (int) (Math.random() * 6)+1;
if(diceValue == 1){
count1++;
} else if (diceValue == 2) {
count2++;
}
else if (diceValue == 3) {
count3++;
}
else if (diceValue == 4 ) {
count4++;
}
else if (diceValue == 5) {
count5++;
}
else if (diceValue == 6) {
count6++;
}
}
그래서 1차적으로 이렇게 변경했다!