如果类型不相等,在重写equals(Object obj)方法时是否值得抛出错误

Is it worth throwing an error when override the equals(Object obj) method if the types are not equal

提问人:GreenFed 提问时间:6/18/2023 最后编辑:M. JustinGreenFed 更新时间:10/31/2023 访问量:13

问:

在 OOP 中,如果类型不相等,在重写方法时是否值得抛出错误?
我想防止对非可比类型进行比较。
equals(Object obj)

问题
例如,我创建了 ValueObject - StudentAge、StudentId 类。
我写检查给学生评分的用户是否与他自己有不同的 id,如果程序员不小心从当前用户的数据而不是标识符中获取有关他的年龄的信息,可能会被错误地写入 - 而编译器不会产生错误。

// Mistake
if(!id.equals(student.getAge()){
// …
}
// Right
if(!id.equals(student.getId()){
// …
}

而且这种错别字经常发生,即使在代码审查期间也可能没有被注意到。 我想防止这种非可比类型的抛出异常,但几乎所有的例子

OOP 平等

评论


答:

0赞 Marc Le Bihan 6/18/2023 #1

为了获得你想要的东西,你只需要在每次定义特定对象(、、...)的equals方法时,检查它们的实例类。
而且,就你而言,当它不是你所期望的时,要变得激烈。
StudentStudentAgeStudentId

例如,对于:StudentAge

public boolean equals(Object o) {
   if (o instanceof StudentAge == false) {
      throw ... your Exception ...
   }

   StudentAge candidate = (StudentAge)o
   return candidate.value == this.value;
}

然后靠着事物的力量,一堂又一堂的课,当你来到:Student

public boolean equals(Object o) {
   if (o instanceof Student == false) {
      throw ... your Exception ...
   }

   Student candidate = (Student)o
   boolean equals = true;
   equals = equals && candidate.studentAge.equals(this.studentAge);
   equals = equals && candidate.studentId.equals(this.studentId);
   ...

   return equals;
}

然后,任何“错误”类型的类都会抛出异常,而不仅仅是返回 false。