Coding pattern c#
c#, refactoring
Solution
I made a little refactoring of your implementation
private void DoTasksWhile(Func<bool> predicate, IEnumerable<Action> tasks)
{
foreach (var task in tasks)
{
if (!predicate())
return;
task();
}
}
- you don't need to `Invoke` delegates. Just execute them
- do not compare boolean values with `true/false` (it's useless and you can assign boolean value by mistake)
- thus you only enumerating tasks, `IEnumerable` is good for parameter
Also you can create extension method
public static void DoWhile(this IEnumerable<Action> actions,Func<bool> predicate)
{
foreach (var action in actions)
{
if (!predicate())
return;
actions();
}
}
Usage will be very simple:
tasks.DoWhile(() => CheckSomeState());
Problem
I came across some code that looked like this in a code review the other day. ``` public void DoSomeTasks() { if (CheckSomeState()==true) return; DoTaskOne(); if (CheckSomeState()==true) return; DoTaskTwo(); if (CheckSomeState()==true) return; DoTaskThree(); if (CheckSomeState()==true) return; DoTaskFour(); } ``` As the number of tasks increases the code ends up with an ever higher cyclomatic complexity and it also just doesn't feel right to me. A solution that I have come up with to resolve this is. ``` private void DoTasksWhile(Func<bool> condition, Action[] tasks) { foreach (var task in tasks) { if (condition.Invoke()==false) break; task.Invoke(); } } ``` Used like this ``` public void DoSomeTasks() { var tasks = new Action[] { {()=DoTaskOne()}, {()=DoTaskTwo()}, {()=DoTaskThree()}, {()=DoTaskFour()} } DoTasksWhile(()=>CheckSomeState(), tasks); } ``` Anyone got any suggestions to make the code more readable?