Search code examples
while-loopcoding-stylepascallazarusfreepascal

How to avoid violating the DRY principle when the boolean expression of a while loop is reassigned every loop pass?


Both

while MyFunction(1, 2, 3) > 0 do
  begin
    Temp := MyFunction(1, 2, 3);
    ShowMessage(IntToStr(Temp));
  end;

and

Temp := MyFunction(1, 2, 3);
while Temp > 0 do
  begin
    ShowMessage(IntToStr(Temp));
    Temp := MyFunction(1, 2, 3);
  end;

violate the DRY principle because there are two calls to MyFunction when only one is necessary.


Solution

  • Easy,

      function dotemp(a,b,c:integer;var value : integer):boolean;
      begin
        value:a*b+c;
        result:=value>0; 
      end;
    
      begin
        while dotemp(a,b,c,temp) do
            begin
               Operateontemp(temp);
             end;
      end;
    

    Pascal has no lvalue assignments, but it DOES have var parameters.