Application of state machine idea in program design

Source: Internet
Author: User

Application of state machine idea in program design author: Zhang June Published: 2015-09-13 12:20 read: 1314 recommendations: 3 [Favorites]

  The concept of a state machine

State machine is an important concept in software programming, and it is more important than this concept to apply it flexibly. In a clear and efficient program, there must be a state machine figure.

For example, a key command resolver, it can be considered as a state machine: a state, the trigger a button after the switch to the B state, and then trigger another key to switch to the C state, or return to a state. This is the simplest example of a key state machine. The actual key resolver is more complicated than this, but it does not affect our understanding of the state machine.

Further, the keystroke action itself can also be seen as a state machine. A small keystroke action includes: release, jitter, Close, jitter, and re-release status.

Similarly, the timing of a serial communication (no matter what protocol it follows, standard serial port or I²C, or whether it is wired, infrared, or wireless) can be seen as a series of finite states.

The display scanner is also a state machine; the communication Command resolver is also a state machine, even if the relay's suction/release control, light Emitting tube (LED) light/out control is not a state machine.

When we open our minds and put the state machine into the program as a thought, we will find an effective shortcut to solve the problem. Sometimes it may be more effective to think about a program with a state machine, than to think in a controlled process. This allows the state machine to have a more practical function.

The program is actually a state machine.

Perhaps you do not understand the above sentence. Think of it that the building of a computer is not built on the foundations of the "0" and "1" two basic states?

  Features of the state machine

State machine can be summed up as 4 elements, namely, present state, condition, action, and sub-state. This induction is mainly due to the internal causal relationship of the state machine to consider. "Present state" and "condition" are the result of, "action" and "sub-state" is the fruit. Details are as follows:

① Present state: Refers to the current status.

② condition: Also known as "event". When a condition is met, an action is triggered, or a state migration is performed.

③ Action: The action performed after the condition is met. After the action is completed, you can migrate to a new state, or you can still remain in the original state. The action is not required, and when the condition is met, you can move directly to the new state without performing any action.

④: The new state to be moved when the condition is satisfied. "Secondary state" is relative to the "present state", the "secondary state" once activated, it becomes a new "present state".

If we further summarize the "present state" and "sub-state" unified, and the "action" ignored (degraded processing), then only two of the most critical elements, namely: state, migration conditions.

There are many ways to represent a state machine, and we can represent a state machine in the form of a text, a graphic, or a table.

It is inefficient to describe it purely in words, so it is not introduced. The next step is to introduce the graphical approach.

  State Migration Diagram (STD)

The state Migration diagram (STD) is a graphical way of describing the state of the system and the relationship between the transformations. There are many kinds of representations of State migration diagrams, but they are generally similar. Let's combine an example to illustrate its drawing, as shown in 1.

Figure 1 State Migration diagram

① Status box: A box representing the state, including so-called "present state" and "secondary state".

② conditions and Migration arrows: Use arrows to indicate the direction of the State migration and to label the trigger condition on the arrow.

③ Node Circle: When multiple arrows point to a state, a node symbol (small circle) can be used to join the summary.

④ Action Box: represented by an ellipse box.

⑤ Additional condition Judging box: With a hexagonal diamond frame.

The state migration diagram has an essential difference from our common flowchart, which is embodied in the flowchart where the arrows represent the jump of the program's PC pointer, whereas in the State migration diagram, the arrows represent a change of state.

We will find that this state migration diagram is more concise, intuitive, and understandable than the normal program flowchart. That's exactly what we need to achieve.

  State Migration Table

In addition to State migration diagrams, we can also represent relationships between States in the form of tables. Such tables are generally referred to as State migration tables.

Table 1 is another descriptive form of the state migration diagram described earlier.

Table 1 State Migration Table

① describes state machines in tabular form, with the advantage of accommodating more text messages. For example, we can not only describe the state migration relationship in the State migration table, but also include the description of each state.

② If the table has more content and is too bloated to read, we can also split the State migration table. The table name varies according to the specific contents of the table after the split.

③ For example, we can separate the status feature from the migration relationship. A table that is individually split to describe a state feature can also be called a "state-of-the-truth". One of the more common is to put a separate list of the display contents of each state. This table, which describes each status display, is called "Display truth tables." Similarly, we refer to a State migration table, which is based on a button, as a "key function truth." In addition, if each state contains too much information, we can also put each state in a separate list.

④ This shows that the State migration table is a useful complement to the State migration diagram, and its expression is flexible.

⑤ State Migration Table The advantage is that the information coverage is large, the disadvantage is not visually intuitive, so it can not replace the state migration diagram. It is ideal to combine graphs and tables. Use a graphic to show the macro and use the table to illustrate details. They are mutually referential and complement each other.

  Implement a clock program with state machine thinking

Next, I'll take a practical example of the application of state machines, combined with flowcharts, state migration diagrams, and state migrations. The following diagram is a diagram of the state migration of a clock program, shown in 2.

Figure 2: Program State Migration Diagram

By summing up this picture, you can get another form of representation-the State migration table, as shown in table 2.

Table 2: Program State Migration Table

  Considerations for state machine applications

Based on the state machine program scheduling mechanism, the difficulty of application is not the understanding of the concept of state machine, but the rational division of the working state of the system.

Beginners tend to treat a "program action" as a "state", which I call "pseudo-state". So how do you differentiate between "action" and "state"? The craftsman's experience is to look at the essence of both: "Action" is not stable, even if there is no conditional trigger, "action" once the execution is finished, and "state" is relatively stable, if there is no external conditions triggered, a state will continue.

Another fatal mistake of beginners is to omit some state when the state is divided, which I call "leaky state".

The existence of "pseudo-state" and "leaky-state" errors will lead to LAX program structure. So be especially careful to avoid it.

More complex state machines

  A simple state structure is described in the previous article. It has only one level and only one dimension, 3.

Figure 3 Linear state machine structure

If necessary, we can build a more complex state machine model.

1. Multilevel State structure

The state machine can be multilevel. In a hierarchical state machine system, a "parent state" can be divided into multiple "sub-states", these sub-states together with the parent state of some common, but also have their own personality.

In some states, sub-States can also be further divided. For example, we can modify the previous clock example as follows:

Combine all the state of the clock function into 1 level states. In this state, can also be divided into 3 two sub-state, respectively, display time, set hours, set the minutes;

In the same way, we can combine all the state of the alarm function with a 1-level state. In this state, and then divided into 4 two sub-state, respectively, to display the alarm, set the "Time", set "Minutes", set the tweet time.

We need to use another state variable (register) to represent these sub-states.

Sub-state of course can also have a lower level of the grandchild State (children and grandchildren endless), thus the entire state system into a tree-like multilevel state structure, 4.

Figure 4 Tree-like multilevel State structure

2. Multidimensional State structure

The state structure can also be multidimensional. The state of the system is divided from different angles, and some characteristics of these states are intersecting. For example, in accordance with the button and Display division state, but also according to the system's work process to make another State division. These two state divisions exist simultaneously and intersect each other, thus constituting a two-dimensional state structure space.

To give an example of this, such as: Air conditioning remote control, 5 is shown.

Figure 5 Multi-dimensional state machine architecture

Similarly, we can build a three-dimensional, four-dimensional or even more state structure. The state of each dimension needs to be represented by a state variable (register).

No matter how fascinating the multilevel state structure and multi-dimensional state structure seem, the artisan's advice is: we still have to simplify the state structure as much as possible, with a single-stage, single-dimension structure, do not give yourself a look, to play the nightmare of complex structure.

The simplest is the most effective.

  Conclusion

The understanding of the state machine requires a process that is more accessible. This process should be combined with practical application and specific case thinking. When a good idea becomes the habit of design, it can give the designer a reward. May this notebook introduction of the state machine based programming ideas can bring some enlightenment to novice, help you find the "program design" feeling.

Application of state machine idea in program design

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.