Joel Min
Joel Min

Reputation: 3457

How to define a boolean expression and evaluate it only when used?

Let's go straight to an example:

public bool MeetsAllConditions()
{
    bool check1, check2, check3;

    // Some code to define result of check1
    if (something...)
    {
        if (something...)
        {
            check1 = true;
        }
    }

    // many more code to define check2 and check3
    ....

    if (check1 && check2 && check3)
    {
        return true;
    }
    return false;
}

Now, the code to define each check is very expensive. Hence I would like to make it so that the code that defines result of each check is evaluated only in the final if statement. This way I can utilise lazy evaluation to save resource if any of the check fails.

How would I approach this without defining a separate method for each check in C#?

Upvotes: 3

Views: 276

Answers (2)

Abhinav Galodha
Abhinav Galodha

Reputation: 9908

Why not use the Lazy<T> ?

From MSDN

Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

Since you have mentioned Expensive Process, why not encapsulate the expensive process in a Type ?

Upvotes: 2

StriplingWarrior
StriplingWarrior

Reputation: 156634

It depends by what you mean by a "separate method". If you're willing to create delegates inline in your code, you could do something like this:

Func<bool> check1 = () =>
{
  if(something...)
  {
    if(something...)
    {
      return true;
    }
  }
}
...

return check1() && check2() && check3();

Another option is simply to short-circuit and return early any time you notice something that should cause you to return false.

if(!something...)
{
  return false;
}
if(!something...)
{
  return false;
}
... // same pattern for check2 and check3
return true;

Upvotes: 3

Related Questions