I have a class ‘Task’ which represents any Task that is done by an individual employee. For this class I wrote properties like EmpID, Priority, etc. and methods like AddNewTask(),
ArchiveTask(),
MoveTaskToUser(int userid),
etc.
Then I wrote a method
public List<Task> GetAllTasks()
This seemed incorrect to me with regard to OOP. I thought any single task object should represent one single task and it doesnt seem right to call taskObj.GetAllTasks()
because object taskObj should carry out methods on the single Task that it represents.
So I changed the method to static:
public static List<Task> GetAllTasks()
Now I call Task.GetAllTasks()
. Is this the proper way to follow object oriented approach. Was the earlier idea of calling the method from single object correct?
The static approach is a good start. You could also just write up a class that manages all tasks. You could then go like:
TaskManager.addTask(/*whatever params are necessary*/);
TaskManager.getTask(/*whatever identifier you desire*/);
TaskManager.getTasksOfEmployer(/*employer-id*/);
TaskManager.getAllTasks();
TaskManager.updateTask();
etc...
9
I have done something similar in the past and I used a TaskList type of object which contained the list of Task objects and manages the addition, removal and retrieval of each of the Tasks. Each Task implemented an ITask interface which had a Name property which was used to retrieve a task.
public interface ITask
{
string Name { get;set; }
void Execute();
}
Each task would implement this interface and as such the class that manages the Tasks does not need to know about any particular, it just knows it can call the Execute method and a Task will carry out its action.
public class TaskList
{
private List<ITask> _taskList = new List<ITask>();
public void Add(ITask task)
{
//Check for null / duplicate task
_taskList.Add(task);
}
public void GetTask(string name)
{
foreach(var task in _taskList)
{
if(task.Name.Equals(name))
return task;
}
throw new ArgumentOutOfRangeException();
}
public void Remove(ITask task)
{
if(_taskList.Contains(task))
_taskList.Remove(task);
}
}
Hope this helps a bit.