问题
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