gpt4 book ai didi

java - 更优雅的 Setter 编码方式

转载 作者:行者123 更新时间:2023-11-29 07:32:29 26 4
gpt4 key购买 nike

我想知道他们是否是编写 setter 的更聪明、更优雅的方式,或者就此而言,是否有任何代码必须检查用户输入是否正确

这看起来很奇怪。我是新手,所以也许这只是解决这个问题的标准方法,但如果不是,我很想知道“聪明”的方法是什么

public void setMonth(){
boolean run = true;
while(run){
int input = scan.nextInt();
if(input > 0 && input < 13){
this.month = input;
run = false;
}
}
}

最佳答案

首先你可以像这样简化你的代码:

 public void setMonth() {
int input = 0;
do {
input = scan.nextInt();
} while(input <= 0 || input >= 13)

this.month = input;
}

除此之外,我将把它分成两个函数。 setter 应该只设置一个值。

 public void setMonth(int month) {
if(month > 0 && month <= 12) {
this.month = month;
} else {
throw new IllegalArgumentException("Month has to be a value between 1 and 12 inclusively. Actual value was :" + month);
}
}

public void readMonth() {
int input = 0;
do {
input = scan.nextInt();
} while(input <= 0 || input >= 13)

setMonth(input);
}

正如 ChiefTwoPencils 所建议的,您还可以将 setter 提取到另一个类中。从而进一步分离用户输入和数据。

 class MonthDataHolder {
private int month;

public MonthDataHolder(int month) {
setMonth(month);
}

public void setMonth(int month) {
if(isValidMonthValue(month)) {
this.month = month;
} else {
throw new IllegalArgumentException("Month has to be a value between 1 and 12 inclusively. Actual value was :" + month);
}
}

private boolean isValidMonthValue(month) {
return month >= 1 || month <= 12;
}
}

class InputReader {

public MonthDataHolder readMonth() {
int input = 0;
do {
input = scan.nextInt();
} while(input <= 0 || input >= 13)

return new MonthDataHolder(input);
}
}

关于java - 更优雅的 Setter 编码方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com