Search code examples
javaoopbidirectional

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.


Solution

  • 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
      }
    }