TimKaechele
TimKaechele

Reputation: 530

Bi Directional Relations in Java

Here's my problem. I have a Task and a Tasklist.

public class Task {
  private Tasklist task list;

  public void setTasklist(Tasklist tasklist) {
   // the code
  }
}

public class Tasklist {
  private List<Task> tasks;

  public void addTask(Task task) {}
  public void removeTask(Task task) {} 
}

What I want is this: I want to update the tasklist once the user changes the tasklist variable of the the task

So if I execute

Tasklist myTasklist = new Tasklist();
Task myTask = new Task();
myTask.setTasklist(myTasklist);

I want to see this.

myTasklist.getTasks(); // => [myTask]

Vice versa if I add a Task to my Tasklist I want it to automatically update the tasks tasklist reference

Tasklist myTasklist = new Tasklist();
Task myTask = new Task();

myTasklist.addTask(myTask);

myTask.getTasklist(); // => myTasklist

I tried to solve the problem on my own, but I always ended up with a stack overflow.

Upvotes: 0

Views: 84

Answers (2)

Jonathan Schoreels
Jonathan Schoreels

Reputation: 1730

... And you ended up on stackoverflow.

Cycle dependency is rarely a good idea. The question to ask yourself is : Can a task exists without a Tasklist ? Can a tasklist exist without knowledge of its tasks ?

The biggest problem is that you would have to deal with the possibility that the Tasklist keeps track of a task which is refered to another Tasklist.

However, for this poblem, you will get a stack overflow if the call you are marking to the TaskList will call something on the Task which will call back the same method of TaskList.

Upvotes: 0

Gee Bee
Gee Bee

Reputation: 1794

A task belongs to a list, a list knows its tasks. Easy stuff - there is only one thing missing: deciding who is adding what to what?

I mean, normally you add a Task to a TaskList, so what is the point to model it on the opposite way? I dare to remove the setTaskList method for the sake of simplicity.

Now it is clearly seen that you add a new task to a tasklist by calling add(). There is only one way to add a task to a tasklist - by calling add(). Once you add a task to a tasklist, this add method updates the task's taskList attribute.

public class Task {
  private TaskList taskList;
}

public class Tasklist {
  private List<Task> tasks;

  public void addTask(Task task) {
      tasks.add(task);
      task.taskList=this; // belongs to this list now
  }
  public void removeTask(Task task) {
      tasks.remove(task);
      task.taskList=null; // belongs to no tasklist
  }
}

Upvotes: 3

Related Questions