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?
I made a little refactoring of your implementation
Invokedelegates. Just execute themtrue/false(it’s useless and you can assign boolean value by mistake)IEnumerableis good for parameterAlso you can create extension method
Usage will be very simple: