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

喜欢而已 提交于 2019-12-12 03:49:34

问题


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.


回答1:


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.




回答2:


I don't quite see the problem. Why don't you invert the logic and forget about Break:

repeat
  Temp := MyFunction(1, 2, 3);
  if Temp <= 0 then
  begin
    //code which uses Temp, for example:
    ShowMessage(IntToStr(Temp));
  end;
until Temp > 0;

That does exactly the same as you first sample, i.e. the while True do code snippet, but neither calls the function twice, nor does it need to use an assignment as an expression (not possible in Delphi), nor does it need to exit early with Break.

In C, you would do this with

do
{
    ...
} while (temp <= 0);

Note that every

if (condition) then 
  Break;

can be replaced by

if not (condition) then
  // rest of original loop.
end;

for the rest of the loop.




回答3:


There is the possibility to use an infinite loop and Break:

while True do
  begin
    Temp := MyFunction(1, 2, 3);
    if Temp <= 0 then Break;
    ShowMessage(IntToStr(Temp));
  end;



回答4:


Temp := 1;
while Temp > 0 do
begin
   //...
end;

Or repeat-until



来源:https://stackoverflow.com/questions/37928523/how-to-avoid-violating-the-dry-principle-when-the-boolean-expression-of-a-while

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!