I have a question that's more of a best practice rather that an actual problem.
Supposed I'm building a projects app and each project would have multiple tasks that need to be completed.
So the projects class:
class Project {
public $id;
public $name;
// Get tasks of this project
public function getTasks() {
// some logic to get tasks of this project
}
// Should a method for adding task go here
public function addTask() {
// some logic going here
}
}
And the tasks class:
class Task {
public $id;
public $name;
// Should a method for adding task go here
public function add_task($project_id) {
// The task class here needs to know the project_id
// to continue with the logic
}
}
As you can tell, any task always belongs to a certain project.
Adding a task should be considered a method for tasks or because any task always belongs to a project, it should part of the project class?? Is there a more correct one? So a task is a task and at the same time it's owned by a project
Single Responsibility Principle
A class should have one and only one reason to change, meaning that a class should have only one job.
If Project class's responsibility is to manage Tasks, addTask
should be a Project method.
Consider the possibility of adding addTask
method to Tasks. This would violate the Single Responsibility for the Tasks class. Task would then represent a task, plus it would then have the responsibility of adding itself to some collection of tasks.