 Mirror

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

 Problem/Question/Abstract:Make simple conditions easier to read and mantainAnswer:Sometimes you have conditions like if condition then  Result := what_everelse  Result := something;Or, even worst, sometimes you have several conditions, like if condition1 then  Result1 := what_ever1else  Result1 := something1;if condition2 then  Result2 := what_ever2else  Result2 := something2;if conditionN then  ResultN := what_everNelse  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 trueMyStr = IFF(TRUE, 'Correct', 'Incorrect');// will return 'Incorrect', since the condition is falseMyStr = IFF(TALSE, 'Correct', 'Incorrect');// will return X if X > Y, otherwise returns YMyInt = IFF(X > Y, X, Y);// will return TRUE, since TRUE or FALSE is TRUEMyBool = IFF((TRUE or FALSE), TRUE, FALSE);// will return 0, since TRUE and FALSE is FALSEMyInt = IFF((TRUE and FALSE), 1, 0);// is MyStr has a lenght grater then 0, returns its lenght, otherwise returns 0MyInt = 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 predecessorMyInt = 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