Title: Making simple conditions easier to read and mantain.
Question: 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
I've been using this funtion for a while and noticed that the code is easier to read and maintain.
Hope it helps you to.