Friday, 17 February 2012

Code Tidbits: Swapping Assignment Variables

Sometimes you come across a situation where you want to assignment 20 or variables, then later on assign them back. Situations like:

  • Class adapter functions
  • Form Load/Save functions
  • Queries. Load from fields, then assign to parameters.

This function will save you from having lots of copy pasta. Run your assignment code through this function, and the variables will be swapped on either side of the assignment operator.

For example:

frmEdit.edtItemPrice.text := Query1.FieldByName('ItemPrice').AsInteger;

becomes
 
Query1.FieldByName('ItemPrice').AsInteger := frmEdit.edtItemPrice.text;

Simply replace the FieldByName with ParamByName and presto!

Query1.ParamByName('ItemPrice').AsInteger := frmEdit.edtItemPrice.text;

Excellent!  And here is the function!

procedure SwapAssignments(Lines: tstrings);
var
  i : integer;
  assignIndex : integer;
  leftstr, rightstr : string;
begin
  for i := 0 to Lines.count - 1 do
    begin
      assignIndex := pos('=',Lines[i]);

      leftstr := copy(lines[i], 1, assignIndex - 2);
      rightstr := copy(lines[i], assignIndex + 1, length(lines[i]) - assignIndex - 1);

      lines[i] := trim(rightstr) + ' := ' + trim(leftstr) + ';';
    end;
end;