IF inmediatos

2819 vistas

Las condiciones booleanas, suelen ser lineas de código simples afectadas por una variable... Puede ser factible crear funciones que permitan controlar ésta situación (hacer en una linea eso que hacemos en 3...)
Estas funciones corresponderÃan al operador ( ? : ) de C o PHP.

Implementación de las funciones:



delphi
  1. Interface
  2.  
  3. { If Inmediato }
  4. { IIF que reenvia un entero }
  5. function IIF(ACondition: boolean; ATruePart, AFalsePart: integer): integer; overload;
  6. { IIF que reenvia un extended }
  7. function IIF(ACondition: boolean; ATruePart, AFalsePart: Extended): Extended; overload;
  8. { IIF que reenvia un string }
  9. function IIF(ACondition: boolean; ATruePart, AFalsePart: string): string; overload;
  10. { IIF que reenvia un objeto }
  11. function IIF(ACondition: boolean; ATruePart, AFalsePart: TObject): TObject; overload;
  12.  
  13. Implementation
  14. function IIF(ACondition: boolean; ATruePart, AFalsePart: integer): integer;
  15. { IF inmediato para enteros }
  16. begin
  17.   if ACondition then
  18.     Result := ATruePart
  19.   else
  20.     Result := AFalsePart;
  21. end;
  22.  
  23. function IIF(ACondition: boolean; ATruePart, AFalsePart: Extended): Extended;
  24. { IF inmediato para floats }
  25. begin
  26.   if ACondition then
  27.     Result := ATruePart
  28.   else
  29.     Result := AFalsePart;
  30. end;
  31.  
  32. function IIF(ACondition: boolean; ATruePart, AFalsePart: string): string;
  33. { IF inmediato para cadenas }
  34. begin
  35.   if ACondition then
  36.     Result := ATruePart
  37.   else
  38.     Result := AFalsePart;
  39. end;
  40.  
  41. function IIF(ACondition: boolean; ATruePart, AFalsePart: TObject): TObject;
  42. { IF inmediato para objetos }
  43. begin
  44.   if ACondition then
  45.     Result := ATruePart
  46.   else
  47.     Result := AFalsePart;
  48. end;



Utilización de las funciones



delphi
  1. procedure TMyObject.TestIIF;
  2. var
  3.   idx: integer;
  4.   MyString: String;
  5. begin
  6.   idx := 10; { Por ejemplo }
  7.   MyString := IIF(idx=0,'Cero','Diferente de cero');
  8. end;



Que serÃa el equivalente a



delphi
  1. procedure TMyObject.TestIIF;
  2. var
  3.   idx: integer;
  4.   MyString: String;
  5. begin
  6.   idx := 10; { Por ejemplo }
  7.   if idx=0 then
  8.     MyString = 'Cero'
  9.   else
  10.     MyString = 'Diferente de Cero';
  11. end;