Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to use if condition

I need to run a test script which has over 10 conditions to verify. If any step fails, the program will fail and further steps won't be executed. Current, my program is like this:

boolean status = 0;

status = function1(param1, param2);
if (status) {
   status = function2(param1, param2);
   if(status) {
      status = function3(param1, param2);
      if(status) {
         status = function4(param1, param2);
      }
      :
      :
      :
   }
} 

return status;

I am not happy with so many embedded IF clauses. Is there a better way to do it?

like image 951
ericyoung Avatar asked Dec 11 '25 21:12

ericyoung


2 Answers

Translated into Perl, you might write:

sub testing
{
    my $status;

    if (($status = function1($param1, %param2)) &&
        ($status = function2($param1, %param2)) &&
        ($status = function3($param1, %param2)) &&
        ($status = function4($param1, %param2)))
    {
        # ...do whatever...
    }

    return $status;
}

Or, given that $status is just a boolean:

sub testing
{
    return 0 if !function1($param1, %param2) ||
                !function2($param1, %param2) ||
                !function3($param1, %param2) ||
                !function4($param1, %param2);

    # ...do whatever...

    return 1;
}

Or:

sub testing
{
    return 0 unless function1($param1, %param2);
    return 0 unless function2($param1, %param2);
    return 0 unless function3($param1, %param2);
    return 0 unless function4($param1, %param2);
    # ...do whatever...
    return 1;
}

If you've really got 10 functions with identical calling signatures, then you might even do:

sub testing
{
    my @funcs = ( &function1, &function2, &function3, &function4, &function5,
                  &function6, &function7, &function8, &function9, &function10,
                );

    for my $funcref (@funcs)
    {
        return 0 unless &$funcref($param1, %param2);
    }

    # ...do whatever...

    return 1;
}

Notice that the first three alternatives will handle divergent function call signatures with just a messier layout of the code; the last pretty much requires the same function call signature on each of the functions in the list.

like image 147
Jonathan Leffler Avatar answered Dec 14 '25 00:12

Jonathan Leffler


return function1($param1, %param2) &&
       function2($param1, %param2) &&
       function3($param1, %param2) &&
       function4($param1, %param2);

This uses a short-circuit to stop evaluation as soon as one of the functions returns a false value.

like image 43
RobEarl Avatar answered Dec 14 '25 00:12

RobEarl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!