I have two classes:
public class CourseModule {
// attributes...
List<Course> courses;
public void addCourse() { ... }
}
public class Course {
// attributes...
CourseModule module;
}
The attributes of Course do not suffice to identify an object uniquely, the course module is always required, also for addition information. A CourseModule consists of difference Courses.
What I don’t like here is the circular dependency, it feels wrong. Now I was thinking about the following, instead of adding courses per method and setting the CourseModule reference by hand I could automate this procedure with the constructor:
public Course(...,...,...., CourseModule module) {
this.module = module;
module.courses.add(this);
}
But again, here is another huge problem: In Brian Goetz Java Concurrency in Practice it is said: Do not let the this reference escape the constructor
So what would be best practice here? I think its a really simple example, which might bear yield a sample solution.
Funnily enough, I had to do something similar. See my question here.
I found this post on the internet that is almost an exact duplicate of what you are trying to do, also with courses! I found that the solution specified there is not 100% right, the answers on my question need to be considered.