Delphi coding hints and tips.

Using const arrays for case like evaluations

Below is an example function using this technique. Given a integer between 0 to 9 it returns a string name of the integer.

function IntToDigit(const n:Integer):string; 
const
  Digits:array[0..9] of string=('Zero','One',
    'Two','Three','Four','Five','Six','Seven',
    'Eight','Nine');
begin
{assumes n is in range 0..9 if not get out of range errors!}
Result:=Digits[n];
end;

It works as we just index out of the array the string equivalent. Another example of this technique could be that based on a TAlignment property we need to determine the Left position for some purpose. TAlignment is defined as enumerated type which mean the compiler will translate it into a range of integers.

TAlignment=(taLeftJustify,taRightJustify,taCenter);

So we could create an const array with a value for each possible value as follows:-

const
  LeftPos:array[TAlignment] of integer=(0,50,100);

Then to determine for any TAlignment the left posistion we would do as follows:-

xPox:=LeftPos[Label1.Alignment];

Using this technique results is fast execution speed as all you are doing is indexing into an array rather than a whole load of IF THEN's or a CASE statement..