我有两种类似的方法来设置矩形的尺寸。起初,我将它们组合成一个设置宽度和长度的较长方法。我读到了保持代码模块化,一次执行一项任务。所以将它分成两种方法。另外,我有单独的方法来显示消息。我是否会将方法分解为较小的方法?
private void userInputWidth() {
Scanner reader = new Scanner(System.in);
double loopCondition = 0;
while (loopCondition <= 0) {
displayEnterWidth();
double nextDouble = reader.nextDouble();
loopCondition = nextDouble;
if (nextDouble <= 0) {
displayErrorMessage();
} else {
this.rectangleWidth = nextDouble;
break;
}
}
}
private void displayEnterWidth() {
System.out.println("Please enter the width of the rectangle ");
}
第二种方法
private void userInputLength() {
Scanner reader = new Scanner(System.in);
double loopCondition = 0;
while (loopCondition <= 0) {
displayEnterLength();
double nextDouble = reader.nextDouble();
loopCondition = nextDouble;
if (nextDouble <= 0) {
displayErrorMessage();
} else {
this.rectangleLength = nextDouble;
break;
}
}
}
private void displayEnterLength() {
System.out.println("Please enter the length of the rectangle");
}