方法markStudent(...)和getUnitMark(...)中的前提条件代码使用了该类的其他方法:isEnrolled(...)和hasCompletedAssessments(...)。
import java.util.ArrayList;
import java.util.HashMap;
public class Unit {
private String code;
private String name;
private HashMap<Integer, Student> enrolledStudents = new HashMap<Integer, Student>();
private AssessmentScheme assessmentScheme = null;
private HashMap<Assessment, HashMap<Student, Mark> > Marks
public Unit(String newCode, String newName) { code = newCode;
name = newName;
}
public void enrolStudent(Student newStudent) {
enrolledStudents.put(newStudent.getPersonID(), newStudent);
}
public void unenrolStudent(Student student) {
enrolledStudents.remove(student.getPersonID());
}
public boolean isEnrolled(Student student) {
return enrolledStudents.containsKey(student.getPersonID()); }
public ArrayList<Student> getEnrolledStudents() {
ArrayList<Student> students = new ArrayList<Student (enrolledStudents.values());
return students; }
public boolean hasCompletedAssessments(Student student) { boolean hasCompleted = true;
for (Assessment a : assessmentScheme.getAssessments()) { hasCompleted &= Marks.get(a).containsKey(student);
}
return hasCompleted; }
public void markStudent(Assessment assessment, Student student, int score, String comment) throws Exception {
/* Start Preconditions */
// Precondition: studentEnrolledInUnit
if (! isEnrolled(student)) {
} throw new Exception("Precondition violated: studentEnrolledInUnit");
// Precondition: scoreInValidRange
if ((score < 0 || (score > assessment.getWeight()) }
throw new Exception("Precondition violated: scoreInValidRange"); /* End Preconditions */
Mark mark = new Mark(assessment, student, score, comment);
Marks.get(assessment).put(student, mark);
}
问题是,前提条件代码中使用的方法(例如isEnrolled(...)和hasCompletedAssessments(...))是公开的还是私有的?
根据我对合同设计的理解,客户应检查其论点是否符合前提条件。这意味着在前提条件代码中使用的方法应该是公共的,以便客户端类可以进行检查。但是,在markStudent方法中,可以清楚地看到该方法正在检查其自身的前提条件。有人可以帮忙吗?
答案 0 :(得分:0)
公开这些方法没有任何危害。 这样一来,客户就可以确保其通话合法。 如果客户知道自己的通话合法,则不必这样做。
方法实现也可以通过调用公共方法自己进行检查。