java - 在java中向类变量添加值的优雅方法

标签 java

我有一个类(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/

相关文章:

java - 缺少 Twitter4j 身份验证凭据

java - Java 导致 Oracle 中存在大量非 Activity session

java - 线程 "main"org.hibernate.InvalidMappingException : Unable to read XML 中出现异常

java - 使用 tomcat 我可以检查我的 HTTP REQUEST 是否是对我的 Web 服务的有效请求?

java - 合并两个 log4j.properties 文件

java - 为 JavaCameraView 使用自定义类会使应用程序崩溃

java:打印当前回溯

java tomcat6 - 添加数据时如何自动刷新页面?

java - 获取没有照片的电话联系人,以便将它们保存在 DataOutputStream(vcf 格式)中

java - 平均值和标准差方法返回 NaN