Mirror

Keep your IF ... ELSE conditions reduced to a minimum (Views: 706)


Problem/Question/Abstract:

Make simple conditions easier to read and mantain

Answer:

Sometimes you have conditions like

if condition then
  Result := what_ever
else
  Result := something;

Or, even worst, sometimes you have several conditions, like

if condition1 then
  Result1 := what_ever1
else
  Result1 := something1;

if condition2 then
  Result2 := what_ever2
else
  Result2 := something2;

if conditionN then
  ResultN := what_everN
else
  ResultN := somethingN;

Woundt it be much easy to write something like

Result := IFF(condition, result_when_condition_is_true,
  result_when_condition_is_false);

What I propose here is a simple function that will reduce simple conditions into a single line, by receiving a condition and the values  to return when the condition is true or false.

function IFF(C: Boolean; T, F: Variant): Variant;
begin
  if C then
    Result := T
  else
    Result := F;
end;

Since the variables are variant type, you can pass any data type you want, like in these examples:

// will return 'Correct', since the condition is true
MyStr = IFF(TRUE, 'Correct', 'Incorrect');

// will return 'Incorrect', since the condition is false
MyStr = IFF(TALSE, 'Correct', 'Incorrect');

// will return X if X > Y, otherwise returns Y
MyInt = IFF(X > Y, X, Y);

// will return TRUE, since TRUE or FALSE is TRUE
MyBool = IFF((TRUE or FALSE), TRUE, FALSE);

// will return 0, since TRUE and FALSE is FALSE
MyInt = IFF((TRUE and FALSE), 1, 0);

// is MyStr has a lenght grater then 0, returns its lenght, otherwise returns 0
MyInt = IFF(Lenght(MyStr) > 0, Lenght(MyStr), 0);

// if 'Address:' is present on MyStr, it will return the lenght of the string, otherwise will return the string 'Not Found!'
MyVar = IFF(Pos('Address:', MyStr) > 0, Length(MyStr), 'Not found!');

// if x is smaller or equal to 1, it returns X, otherwise it returns the multiplication of X by its predecessor
MyInt = IFF(X <= 1, X, X * (X - 1));

I've been using this funtion for a while and noticed that the code is easier to read and maintain.

<< Back to main page