为了更好地说明这个问题,举个例子:假设我们有一个学生管理器,由一位教授负责,他将学生对象添加到列表中。创建新的学生对象时,我们必须检查他的名字是否最多20个字符长。
class Professor{
LinkedList<Student> studentsList;
Professor(){
studentsList = new LinkedList<Student>();
}
public Student addStudent(String studentName){
// Place 1
if (studentName.length <= 20)
studentList.add(new Student(studentName));
else
// Do another thing
}
}
class Student {
String name;
Student(String studentName){
// Place 2
if (studentName.length <= 20)
name = studentName);
else
// Don't create the object and throw exception
}
}
基本上我的问题是,在尝试创建学生之前,应该在"地点 1"进行检查,还是在学生构造函数中的"地点 2"进行检查。
name
可以在构建后修改。我们只能根据提供的代码来回答问题。 - shmosel