mercredi 10 février 2016

Call any one of a number of functions until re get a specified result

I've got this ugly bit of code that looks a bit like this ...

TestResult GetFirstTestResult()
{
    var result = TestMethod1();
    if(result is EmptyResult)
    {
        result = TestMethod2();
    }

    if(result is EmptyResult)
    {
        result = TestMethod3();
    }

    // ...

    if(result is EmptyResult)
    {
        result = TestMethodN();
    }

    return result;
}

Basically, I need to run a number of tests until I find one that has some values.

Now whilst the above code isn't pretty, for a small(ish) value of N is is managable. Sadly, in my case, N could get fairly big.

Is there a way of writing this using a loop, something along the lines of this pseudo code...

TestResult GetFirstTestResult()
{
    TestResult[] results = {TestMethod1(), TestMethod2(), TestMethod3(), .. TestMethodN()};
    return results.First(test=>!test.Result is Emptyresult);
}

such that each of the test methods were invoked in the loop so only the minimum number of them were actually executed?

Aucun commentaire:

Enregistrer un commentaire