我有一个类(class)说 Student
public class Student {
private String name;
private int score;
}
假设我有所有的 getter/setter。
目前,我有一个学生类的对象 say std
,它的得分值为 50。
我想给这个对象的分数加 10。
我可以通过下面的代码做到这一点:
std.setScore(std.getScore() + 10);
我正在寻找一种优雅的方式来编写相同的代码,其中我不使用 getter 和 setter,并且可以将分数增加 10 甚至 1。 比如说使用++ 或类似 +=10 等。
最佳答案
写一个方法:
public void incrementScore(int amount) {
score += amount;
}
是否允许负增量?如果没有,检查一下:
/**
* Increments the score by the given amount.
*
* @param amount the amount to increment the score by; must not be negative
* @throws IllegalArgumentException if the amount is negative
*/
public void incrementScore(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("The increment must not be negative.");
}
score += amount;
}
这种方法比使用 get
/set
更优雅,因为:
- 它允许您根据业务规则再次检查论点,
- 它添加了一个业务方法,其名称显示了意图。
- 它允许您编写 JavaDoc 注释来描述操作的确切行为
关于java - 在java中向类变量添加值的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55101029/