Lazarus / Free Pascal:如何改进一个while循环的编码风格(避免使用无限循环),该循环的布尔表达式被重新赋值每遍 [英] Lazarus/Free Pascal: How to improve coding style (to avoid using endless loop) of a while loop whose boolean expression is reassigned every pass
问题描述
目前,我的代码如下所示:
while True do
begin
Temp := MyFunction(1, 2, 3);
if Temp > 0 then Break;
//code which uses Temp, for example:
ShowMessage(IntToStr(Temp));
end;
(高度抽象当然...)
(Highly abstracted of course...)
我认为而True 是不好的风格,因为你不会立即看到循环的布尔表达式,必须搜索
I think while True
is bad style, because you won't see the boolean expression for the loop right away and have to search for the Break;
statement.
while MyFunction(1, 2, 3) > 0 do
begin
Temp := MyFunction(1, 2, 3);
//code which uses Temp, for example:
ShowMessage(IntToStr(Temp));
end;
(因为 MyFunction(1,2,3);
get被调用了两次。)
(Because MyFunction(1, 2, 3);
get's called twice.)
也不是:
Temp := MyFunction(1, 2, 3);
while Temp > 0 do
begin
//code which uses Temp, for example:
ShowMessage(IntToStr(Temp));
Temp := MyFunction(1, 2, 3);
end;
(因为如果我必须更改 MyFunction(1,2,3) ;
到 MyFunction(4,5,6);
,我必须将它改为两行。)
(Because if I have to change MyFunction(1, 2, 3);
to MyFunction(4, 5, 6);
, I have to change it in two lines.)
也不是这个选择:
function AssignTempValue: Boolean;
begin
Result := False;
Temp := MyFunction(1, 2, 3);
if Temp > 0 then Result := True;
end;
(...)
while AssignTempValue do
begin
//code which uses Temp, for example:
ShowMessage(IntToStr(Temp));
end;
(因为一个函数的实现只是为了这个目的似乎过分。)
(Because the implementation of a function solely for this purpose seems overkill.)
有任何想法吗?
EDIT:
好的。我理解,编码风格是高度主观的,每个人都有个人喜好。我的问题不应该理解为:什么是最好的方法? (这是主观的),但是:我怎么能写上面的代码?
Alright. I understand, that coding style is highly subjective and everyone has personal favorites. My question should not be read as: "What's the best way?" (which is subjective), but: "How else could I write the code above?"
:
EDIT 2:
也许有一些方法可以将语句转换为表达式?
Maybe there is some way to turn a statement into an expression?
while (Temp := MyFunction(1, 2, 3)) > 0 do
begin
//code which uses Temp, for example:
ShowMessage(IntToStr(Temp));
end;
推荐答案
为什么不颠倒逻辑并忘记Break:
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;
这与第一次采样完全相同,即 while True
代码片段,但是既不调用函数两次,也不需要使用赋值作为表达式(在Delphi中不可能),也不需要提前退出Break。
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.
在C中,您可以使用
do
{
...
} while (temp <= 0);
请注意,每个
if (condition) then
Break;
可替换为
if not (condition) then
// rest of original loop.
end;
用于循环的其余部分。
这篇关于Lazarus / Free Pascal:如何改进一个while循环的编码风格(避免使用无限循环),该循环的布尔表达式被重新赋值每遍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!