Suppose I have a TeacherRepository that needs to make use of a CourseRepository per the code below. Teacher and Course form a many to many relationship. Teacher and Course do not form an aggregate. Would you consider this proper use of the pattern?
class TeacherRepository {
@Inject(@Named("courseRepository"))
private final CourseRepository courseRepository;
public void addCourseToTeachers(String courseName) {
Course course = courseRepository.findByName(courseName);
for (Teacher teacher : readAll())
teacher.addCourse(course);
}
}
I don't think it is the task of the TeacherRepository
to deal with courses. IMHO it would be better to handle this in a separate class. It is better to keep a single responsibility for every class.
But if you absolutely want to add this functionality to TeacherRepository
, you can do it without any dependency to CourseRepository
:
class TeacherRepository {
public void addCourseToTeachers(Course course) {
for (Teacher teacher : readAll())
teacher.addCourse(course);
}
}
...
CourseRepository courseRepository = ...;
TeacherRepository teacherRepository = ...;
...
Course course = courseRepository.findByName(courseName);
if (course != null)
teacherRepository.addCourseToTeachers(course);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With