Can I set the state inside a function?

I have this code:

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;
        ...
        ...
        ...

I would like to put code that sets state to stError inside the IncAttempts procedure, as a result:

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;
        ...
        ...
        ...

So, can I move the code to IncAttempts?

Is that the smell of code?

If so, can you advise me the best way?

+3
source share
3 answers

I would see this as perfect valid code. I ask myself the following questions when declaring a method inside another. In most cases, I do not do this, but sometimes this leads to better code.

  • Will the inner function ever change, as in the descendant class?
  • Can I override the external method without calling the internal method, and is everything okay?
  • ?
  • , ?

- .

, , / , .

+4

, . Attempts, , State . , . /.

+2

, ...

, , . , , .

, , :

, .

, , stReadDeviceID.

, while True do - if State = stError then Break;, , stError , . , stError - case -statement ...

GoF, :

0

Source: https://habr.com/ru/post/1787994/


All Articles