我该如何建模? [英] How do I model something like this?
问题描述
我遇到了机器问题,这是一些棘手的部分之一,这使我有些困惑.
I have this machine problem, and here is one of those tricky parts which gets me a little confused.
这是用例:
学生报名参加一节.
系统不会验证任何计划冲突.
系统验证学生已达到要求的先决条件.
Here is the use case:
Student enrolls in a section.
System verifies no schedule conflicts.
System verifies that the student has taken the required prerequisite(s).
因此,我创建了4个对象,分别是Student,Section,Schedule和Subject.
我只向您展示我的主题"课程,因为这让我感到困惑.
So I created 4 objects, called Student, Section, Schedule, and Subject.
I'll only show you my "subject" class because this is where I got confused.
让我感到困惑的部分是:
系统验证学生已达到要求的先决条件.
The part where I get confused is this:
System verifies that the student has taken the required prerequisite(s).
如何正确建模? 我有一个前提条件,它是一个主题对象,但是如果主题没有前提条件,该怎么办?我有些犹豫,因为我不能只做类似的事情:
How do I properly model that? I got a prerequisite which is a subject object, but what if the subject has no prerequisite? I hesitate because I cannot just make something like:
Subject math01 = new Subject(1,"math01",null);
我认为在对象上传递null是不合适的.我想避免nullpointer异常.我该如何解决? :( 我想我做错了.
I think passing null on objects is inappropriate. I'd like to avoid nullpointer exceptions. How do I resolve this? :( I think I'm doing it wrong.
public class Subject {
//Each subject is worth three (3) units.
private int units = 3;
private int subjectID;
private String subjectName;
private Subject prerequisite; //<----How do I express that a subject has a prerequisite? Am I doing this right?
public Subject(int subjectID, String subjectName, Subject prerequisite) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.prerequisite = prerequisite;
}
public int getUnits() {
return units;
}
public int getSubjectID() {
return subjectID;
}
public String getSubjectName() {
return subjectName;
}
public Subject getPrerequisite(){
return prerequisite;
}
public boolean conflictWith(Subject newSubject){
return (this.subjectID == newSubject.getSubjectID());
}
}
推荐答案
考虑添加第二个不需要先决条件的构造函数.然后,您不必从API客户端传递null.
Consider adding a second constructor that doesn't take a prerequisite. Then you don't have to pass in null from the client of your API.
我还将添加一个方便的方法hasPrerequisite(),以检查Subject是否确实具有先决条件.这样,您的API客户端也不必自己进行null检查.
I'd also add a convenience method hasPrerequisite() for checking to see if the Subject does have a prerequisite. That way clients of your API also don't have to do a null check themselves.
这篇关于我该如何建模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!