我有这样的代码:我可以在一个函数中设置一个状态吗?
procedure EstablishCommunication;
var
State : TStates;
Attempts : Byte;
procedure IncAttempts;
begin
Inc(Attempts);
end;
begin
State := stReadDeviceID;
Attempts := 0;
while True do
begin
if Attempts >= MAX_ATTEMPTS then
begin
State := stError;
end;
case State of
stReadDeviceID:
begin
// some code
IncAttempts;
end;
stError:
begin
// Error code
end;
...
...
...
我希望把该程序IncAttempts内设置状态stError,造成代码:
procedure EstablishCommunication;
var
State : TStates;
Attempts : Byte;
procedure IncAttempts;
begin
Inc(Attempts);
if Attempts >= MAX_ATTEMPTS then
begin
State := stError;
end;
end;
begin
State := stReadDeviceID;
Attempts := 0;
while True do
begin
case State of
stReadDeviceID:
begin
// some code
IncAttempts;
end;
stError:
begin
// Error code
end;
...
...
...
所以,我可以将代码移到IncAttempts?
这是代码味道吗?
如果是的话,你可以给我一个更好的方法吗?
它取决于..状态是一个局部变量,所以当max_attempts被创建时,你的过程会做什么?它看起来像是一个错误条件,是引发异常的好地方。但是,总是取决于... – jachguate 2011-01-26 18:03:50
这是一块有限状态机。我正计划在stError状态中引发一个异常。我编辑了代码,试图更好地解释。 – 2011-01-26 18:19:51