I've got faced with this very basic thing multiple times now, but I never knew how to solve it in the most efficient way.
I have a class 'Student' and a class 'Course'. The student should know all of his courses he visits by a list of courses, and the course should know all the students wich are visiting it by a list of students.
Now let's say I want a student to visit a new course, so I create an 'addCourse(Course course)' method to add a new course to the student's list of courses - no problem. But I also want the course to know about the student is visiting it now. So I create a 'addStudent(Student student)' method for the course class and call it in the student's 'addCourse' method.
The problem is: I want to make those data updates possible from both sides - the students and the courses, but if I would add the respective other method into the own method, I would end up in a stack overflow of course. So how can I prevent this most efficiently?
Also if I store this data in objects of both classes, I guess I would flood my memory with more data than I need. Is there a way to prevent this too without losing access to data?
You have a Student
class that has an AddCourse
method, which updates the list of courses that the student visits.
You have a Course
class that has an AddStudent
method, which updates the list of students who are visiting the course.
Somewhere else in your program, you decide that the student is going to visit a course. For example, there might be a user interface that the student interacts with if he wants to join a course. That user's action should trigger a call to some business logic that does everything required to add the student to the course. For example:
function AddStudentToCourse(studentId, courseId)
{
student = GetStudentById(studentId);
student.AddCourse(courseId);
course = GetCourseById(courseId);
course.AddStudent(studentId);
}
The point here is that as far as the Student
is concerned, it just maintains a list of course Id numbers. The Student
class doesn't actually do anything with the courses; it just maintains the list so that some other piece of code can refer to it later.
Same for the Course
; it just maintains a list of student Id numbers.
The beauty of this design is that Student
and Course
are independent of each other, except for those lists of ids; and those are really just numbers.
I won't say that this is "the most efficient" way to do it. It does work well, though.