Reputation: 13278
I have three simple classes for illustration. People have many Projects which have many Tasks.
public class Person {
private ArrayList<Project> projects;
public Person() {
projects = new ArrayList<Project>();
}
public printTasks() {
//TODO
}
}
public class Project {
private String name;
private ArrayList<Task> tasks;
public Project(String name) {
this.name = name;
tasks = new ArrayList<Task>();
}
public getName() {
return name;
}
}
public class Task {
private String name;
private String description;
public Task() {
tasks = new ArrayList<Task>();
}
public getName() {
return name;
}
public getDescription() {
return description;
}
}
My problem relates to what would be the best way to implement Person.printTasks()..I want to display on stdout a list of the project names a person has and after each project, a list of the task names + descriptions that project has.
Is there a best way to handle this or does it really not matter? Personally, I am leaning towards 2) because 1) ties the idea of how an object should be displayed to that object but it feels like this should be decided in a single place i.e. Person. That way I can easily change from stdout to a file for example. 3) gives Person direct access to Task, a class which it previously was not coupled to (at least it was only coupled indirectly through Project).
Is there a better solution than these 3?
Note: This could be a language-agnostic question but I happen to be writing in Java and I imagine that there very well could be different best solutions for different languages so I would like answers to at least address this problem with regards to Java.
Upvotes: 2
Views: 150
Reputation: 13164
Visitor pattern: nobody knows how to print and what to print. You just give project/person/task in whatever relationsship they are a visitor object. project/person/task iterate over objects they own/know about and pass the visitor to them.
The visitor does the right thing - it knows how to access information from objects it visits and if the information should be printed and where: console/file/database or whatever, it also know how to format: xml/html/plain text/csv come to mind as examples.
This was you are free to design your project hierarchy whatever you will, change printing target and formats etc.
Upvotes: 2
Reputation: 114777
If it's for displaying task names only and you don't want Person
depend on Task
, then I suggest adding a method
List<String> getTaskNames();
to the Project
class. That's what a project should be able to tell: the names of its tasks.
Or create an extra TaskMetaData
class, that holds all properties, a person needs to know about a task, and return a collection of TaskMetaData
objects. I'd prefer that over concatenating Strings.
Upvotes: 0