【问题标题】:Should precondition methods be public or private?前置条件方法应该是公共的还是私有的?
【发布时间】:2019-06-13 06:34:51
【问题描述】:

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 方法中,可以清楚地看到该方法正在检查自己的前提条件。有人可以帮忙吗?

【问题讨论】:

    标签: oop design-by-contract preconditions


    【解决方案1】:

    公开这些方法并没有什么坏处。 这使客户能够确保他们的电话是合法的。 如果客户知道他们的电话是合法的,他们就不必这样做。

    方法实现也可以通过调用公共方法进行自己的检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-12
      • 2012-03-14
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 2013-06-24
      • 2012-03-12
      • 2022-12-07
      相关资源
      最近更新 更多