Suppose we want to model students which attend courses. Every student should attend at most one course at a time and a course can contain multiple students (a typical 1-to-n association). Suppose further that this association should be bidirectional, i.e. we should be able to navigate from student to course and vice versa.
So naturally we would have two classes, Student
(holding a reference to the assigned course) and Course
(containing a collection of students). But how do we compose the object graph? Specifically, which operations on which classes should we define to establish a link between a student and a class? The first obvious option would be to define a generic Add
method on the Course
class:
class Course
{
public void Add(Student student) { ... }
}
But you could equally define an operation on the Student
class instead:
class Student
{
public void Attend(Course course) { ... }
}
(Surely there are more options, like passing an instance of the Course
class to the constructor of Student
, but that is not the point here)
Comparing these two alternatives, personally I find the second option more attractive because student.Attend(course)
conveys more information than course.Add(student)
, since Attend
has more meaning than the generic Add
. However I have not yet encountered a single API which uses this style of adding an element to a container object, which leads me to the conclusion that I am missing something important.
So, except that the second option is not very common, what are its drawbacks? Or is it not as uncommon as I think it is?