How can I improve up this code?
Is it ok to write code using Invoke
and Action
so liberally or is this bad?
Performance is not an issue as I'm not using Invoke
50,000x in a a row (a lot of other things will be done in-between, making the performance hit null).
The primary goal is to run my list of tasks either by Item first or task first. The secondary goal is to NOT write a massively long method where each method is written out in each way they can be completed. Doing so makes adding new tasks later much easier.
Code: (Updated with pseudo extras)
public class TaskObject
{
public bool RunPerItem = true; //PLACEHOLDER, normally derived externally from view model
public bool RunPerTask = false; //PLACEHOLDER, normally derived externally from view model
public Dictionary<string, Item>() TaskItems = new Dictionary<string, Item>()
{
{ "ItemA", new Item() {} },
{ "ItemB", new Item() {} },
{ "ItemC", new Item() {} },
}
private List<Action<TaskObject, Item>> Tasks = new List<Action<TaskObject, Item>>()
{
(TO, I) => { TO.TaskA(I); },
(TO, I) => { TO.TaskB(I); },
(TO, I) => { TO.TaskC(I); }
};
public void RunTasks()
{
//RunPerItem & RunPerTask are type `bool`
if (this.RunPerItem)
{
foreach (var I in this.TaskItems)
{
foreach (var T in this.Tasks)
{
T.Invoke(this, I.Value);
}
}
}
else if (this.RunPerTask)
{
foreach (var T in this.Tasks)
{
foreach (var I in this.TaskItems)
{
T.Invoke(this, I.Value);
}
}
}
}
public void TaskA(Item I) { /*...*/ }
public void TaskB(Item I) { /*...*/ }
public void TaskC(Item I) { /*...*/ }
}
public class Item
{
public string ItemName { get; set; }
}
Thanks for any advice/help!!!
Edit/Clarification/Extra Details:
The above code describes 2 different loops with different orders of task completion.
Example Orders:
this.RunPerItem
ItemA
-TaskA
-TaskB
-TaskC
ItemB
-TaskA
-TaskB
-TaskC
this.RunPerTask
ItemA
-TaskA
ItemB
-TaskA
this
refers to the object that containsRunTasks()
. I didn't include the entire object as it's pointless to my example. I'll update my code with some extra pseudo code. \$\endgroup\$foreach
statements are ordered the opposite of the first set ((foreach item -> foreach task), (foreach task -> foreach item)), and the task always processes the item the same way in the end (T.Invoke(this, I.Value);
). \$\endgroup\$