问题
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).
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);
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());
}
}
回答1:
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.
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.
回答2:
Use Null Object pattern. My recommendation is for you to use Guava library so that you can use the Optional class. Here is the tutorial explaining its usage.
来源:https://stackoverflow.com/questions/8730313/how-do-i-model-something-like-this