Search code examples
javaif-statementreturnstate-machine

How to make my code cleaner (return statements)


I am programming a simple state machine as practice. When I have a lot of states with conditions it becomes too unreadable in my opinion. I want to see in the blink of an eye what state I am returning.

Example how it is now:

if  ((currentState.equals(State.s70_SupplyFanStart)) && (/**Some statement*/)); Or
        ((currentState.equals(State.s80_ControlStart)) && (/**Some statement*/)); Or
        ((currentState.equals(State.s90_LimitMonitoringStart)) && (/**Some statement*/)); Or
        ((currentState.equals(State.s99_Fault)) && (/**Some statement*/)); Or
        ((currentState.equals(State.s100_Interlocked)) && (/**Some statement*/));{
            return State.s00_StandBy;
}
    

The above code cant be folded properly, only the return is folder. So, you continue to see all this:

if  (((currentState.equals(State.s70_SupplyFanStart)) && (/**Some statement*/)); Or
    ((currentState.equals(State.s80_ControlStart)) && (/**Some statement*/)); Or
    ((currentState.equals(State.s90_LimitMonitoringStart)) && (/**Some statement*/)); Or
    ((currentState.equals(State.s99_Fault)) && (/**Some statement*/)); Or
    ((currentState.equals(State.s100_Interlocked)) && (/**Some statement*/)); {...}
       

What I for example would like to see is something like this:

return State.s00_StandBy IF {
    /**statement_1 = true or */
        /**statement_2 = true or
            /**statement_3 = true;*
}

so if you fold it you will only see something like this:

return State.StandBy IF {...}

in the end it would be much better to find certain states when they are lined up like this:

return State.StandBy IF {...}

return State.s70_SupplyFanStart IF {...}

return State.s80_ControlStart IF {...}

return State.s90_LimitMonitoringStart IF {...}

etc..


Solution

  • You can model your states as an enum, and encapsulate the transition logic inside the enums.

    So you instead call:

    return currentState.nextState();
    

    Your enum would be something like:

    public enum State {
    
        s70_SupplyFanStart {
            @Override
            public State nextState() {
                // if...
                return ...;
            }
        },
        s80_ControlStart {
            @Override
            public State nextState() {
                // if ...
                return ....;
            }
        },
        ....
    
        public abstract State nextState(); 
    }
    

    See for example: https://www.baeldung.com/java-enum-simple-state-machine