shortcut of multi-conditions with and in AL and Business Central?

579 views Asked by At

Suppose we've procedure is_even return if the number given is even or not!
that's a good code:

if is_even(22) = true or test(1) = true  or test(2)  = true then
    //...

And even that's a better:

if true in [ is_even(22), is_even(1), is_even(2) ] then
    //..

But what if I would do that but with logic(and not or) like that

if is_even(22) = true and test(1) = true  and test(2)  = true then
    //...

Better code would be?

I've tried to do that, So I think of do that with a function like in python all:

local procedure all(array_bools : ARRAY [3] OF Boolean): Boolean
var
    bool: Boolean;
    i: Integer;
begin
    REPEAT
        bool := array_bools[i];
        if bool = false then 
            exit(false);
        i := i + 1;
    UNTIL i <> ARRAYLEN(array_bools);
    exit(false);
end;

and it is not working as I expect

if all([is_even(22), is_even(1), is_even(2)]) = true then
2

There are 2 answers

0
JohnnyUndercover On

I like to keep it simple and readable. I think your code is hard to read because you combine all these checks in to one. Instead i would write something like this:

local procedure CheckMyConditions(): Boolean
begin
    if is_even(22) then
        exit(true);
    if test(1) then
        exit(true);
    if test(2) then
        exit(true);
    exit(false);
end;

Also this would perform better, because AL does not support lazy evaluation. This means every statement between "if" and "then" will be evaluated.

0
Wilhelm Groß On

The best for this cae ist here: if is_even(22) or test(1) or test(2) then