In what context is the state machine pattern indicated?

Asked

Viewed 146 times

9

I have been researching some state machine implementations and would like to know in which situation the state machine fits and what benefit to use it?

2 answers

8


Introducing

Programming is about finding an automated solution to a problem. Certain types of problems in programming, involving entities transiting at each moment to a different state within a finite set of possible states, can be modeled (represented) in the form of a state machine finite, which is basically a certain kind of diagram that I’m going to describe. This representation in principle does not get to the merit of how this problem will be solved in the code, but facilitates this transition, suggesting an algorithm and eventually some abstractions.

The definition of finite state machine (FSM) may be stricter than that, but I will try to explain in a more visual way.

I’m also not getting into the merit of the other type of state machine, which are the state machines infinite. As we see here in Sopt, it is common that when speaking about the state machine in programming is understanding finite.

Well. Once the problem or scenario in question is modeled, the form of implementation will essentially depend on the type of application you are developing, the programming paradigm(s) adopted (in other words, the language) and, of course, the problem itself.

What it is and where it applies

It’s a very simple concept actually, in general it makes sense to model the problem as a finite state machine when you have an entity (any "thing" that can at any time be in a given state within a set of several possible states, as in the case of a lamp (on or off), a semaphore (red, green, yellow, and do not forget also the "defect" state) or other such things (I actually think that three or more states is more common, if there are only two we tend to get by with booleans to solve the problem), and there is a criterion for passing from one state to another that respects a certain logic and also actions that must happen when one reaches an "X" state, as well as the logic for choosing which will be the next state.

Any situation involving some type of flow or steps (whether mandatory or optional), where there is a starting and an arriving stage or the transitions from one to the other in cycle, may fit to apply the idea of finite state machine, that is just a game of connect-the-dots with balls and arrows (the balls are the possible states, and the arrows are the transitions from one to the other, usually with the criterion for the transition to occur noted near each arrow).

If you want to see what it looks like, there’s a picture below.

Benefits

It may be interesting to model the solution this way because that’s what the problem represents, so that would be the advantage, the modeling of the solution to be closer to the representation of the problem and therefore easier to implement, extend and maintain. The diagram understands an algorithm that can be implemented clearly.

Another possible benefit is to take advantage of the abstractions it suggests. In object orientation for example, if you implement the concept of "state" as an object, you may find it interesting in your code to keep the choice of the transition criterion linked to the object that represents that state. It can also take advantage of inheritance and polymorphism to add new states that were not initially foreseen and invoke its methods in order to obey the Open/Closed principle (open to extension, closed to modification).

Ways to implement

The implementation itself can be done in several ways, it will depend on the problem and the type of application you are developing.

If it’s to work on a thread (execution line) only, can be done for example with a simple switch(estadoAtual) contained in a loop, to check the current status and each case perform certain actions when arriving at that state, followed by the logic of changing from one state to another, which will vary depending on the situation.

May also be ifs:

https://i.ytimg.com/vi/RosjDcNoqmk/maxresdefault.jpg (Very simple example of visualizing that I took shamelessly from the Internet)

Or also using certain design patterns, if I’m not mistaken the pattern State is one that can be applied in this scenario. Another possible according to the case is the Builder, which consists in building an object in gradual steps.

Examples of use

Status machines make sense in several scenarios, for example in a context of establishing or authenticating a network connection where a Handshake ("handshake" between parties that involves several steps) and implies in several intermediate states that each side can assume (as occurs at the level of TCP protocol implementation, or at the level of SSL/TLS protocols, or even at the level of the final application according to the authentication protocol that is being implemented), in fact not only the Handshake but the whole life cycle of connection.

Or in the context of executing any sequence of steps and assuming intermediate states (a possible example would be a shopping cart or purchase process on a e-commerce or of delivery, that on the server side would be good candidates for a Builder).

Just remembering that a state machine is not necessarily sequential, it can be cyclic or contain transitions from one state to another that form cycles or even a state to itself, not to get the wrong idea on account of those examples that I finally quoted that were more sequential.

Two other cases for machine states are the life cycle of a "task" in a modern operating system (e.g.: created, ready p/run, running, locked, finished, etc.) and implementations of loops in a single thread that makes available without abstracting too much the non-blocking I/O features made by the operating system in order to achieve greater scalability in applications that perform too much I/O, for example through the Java NIO library that is the basis for scalable network communication frameworks such as Netty and Apache MINA, as well as newer Tomcat versions, or as I suppose is done on Node.js to meet a large volume of Web requests from a single thread.

  • Thanks for the reply @Piovezan, gave to clarify the subject.

  • " A state machine is not necessarily sequential, it can be cyclic and also have internal loops" @Piovezan I imagine that you used this to illustrate your explanation only, but a state machine has no cycles, sequence or some kind of internal or external loop. It has at least 1 state and perhaps a transition rule to some other state. A finite machine of FSA states can have two states for example: on and off. and oscillate between the two. This is not a loop. From a design point of view each state is self-sufficient.

  • @arfneto I called loops in this case the eventual sequences of cyclic transitions, not the loops in the implementation code, if that’s what you meant. Cycles between states or a state for himself I believe he has yes: https://blog.markshead.com/869/state-machines-computer-science/ Anyway I’m not being very strict in the conceptualization and I may have said something wrong.

  • @Piovesan I understand the idea. I think the author you mentioned also wanted to simplify. I read the article. I think the idea of a loop does not apply to a WSF --- and I think that even as this Mark comes to nod, what really matters is a deterministic state machine. And in this case each state has an objective rule of succession, which may be the only state, after all 1 is finite. And you can completely implement a state just by keeping the machine and the context. That’s the thing about this Pattern design. In a communication protocol for example a group can implement up to a certain state only

  • @Piovezan and another group move on after the authenticated session. That’s the value of this thing: being able to program some states and move on. Maybe we should have an example. I’ll see if I have something available here

  • @arfneto If you want to add, I suggest to do it in the form of another answer. Mine is very informal and I think it has stayed up a little big. I think what I’m defining is a real WSF.

  • @Piovesan is right. I wrote an example for someone the other day and should serve. I will see where it is. Hug

Show 2 more comments

2

Didactic response to understand what is and why is important.

You will see this in the world to apply later on in software or circuit design.

Port > (has two states Open or Closed) - Whereas it is properly "installed" heheheh.

Think now of a Switch (On / Off) that ACTS in the state of another object called Lamp. (is transiting between these two states forever) - of course to simplify I did not consider her condition: Burned.

Now, bringing to the present day, think of a temperature sensor connected to an Arduino board: (off) (on) (incommunicable) - possible states. Example: when the sensor is incommunicable, had no answer when trying to get the temperature, you have to make some decision: send the email to someone change that sensor, warn, register in a system log, finally (by itself THE STATE OF IT, may interfere with the WHOLE behavior of the system). That’s why defining the state of objects is so important.

UML state machine diagrams serve to enable you to map all possible states of a given object (whether real-world object or software object).

The interesting part is that you can observe the application of state machine diagrams in / Iot circuit designs. Example: If the temperature sensor state is "defective", make a specific decision or modify the state of another object that is part of the system as a whole.

The importance of this is not to "forget" all possible possibilities and states and end up letting some project situation pass.

Imagine now any e-commerce system. In it surely there is the REQUEST object.

The order can transit between the different states: INVOICED (the customer has just made and paid - a new order with the tax note already generated) - IN SEPARATION (in the logistics sector to be dispatched) - ON THE WAY (being transported) - DELIVERED / LOST OR STOLEN BY POST hahahahahahhahaha (personal is a joke - just not to forget the example)...

Important you understand: Each time a given object changes state, it can interfere with systemic behavior as a whole or other objects and parts of a system and, answering its question: It is important to design or at least raise all possible states of important system objects so that you do not forget important details or unforeseen design situations HOW FAR AHEAD.

Want to see a cool exercise? Status of a Wifi surveillance camera. Think of her status machine (not on/off not ... it is interesting).

  • Dude, I like the analogies :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.