1

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.

Mahoni
  • 7,088
  • 17
  • 58
  • 115
  • Does the Course need to know its CourseModule? – Behe May 05 '12 at 08:08
  • How about in `courses.add(new Cource(..., this))` in module? What you are setting up is a bi-directional parent-child (or container-containee) relation. – rsp May 05 '12 at 08:22

2 Answers2

0

You're right, I would say that your current setup is an example of Code Smell.

Could you not make another object CourseInfo that manages the additional course information that you say cannot be contained within Course?

public class CourseModule {

    List<Course> courses;

    public void addCourse(Course course) { ... }
}

public class Course {

    CourseInfo info;
}

public class CourseInfo {

    CourseInfo info;
}
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
0

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.

Community
  • 1
  • 1
MarioDS
  • 12,895
  • 15
  • 65
  • 121