State model versus ENUM

From time to time, it must maintain state for objects. As far as I understand, there are two approaches:

  • ENUM (SIMPLY)
  • STATE pattern (OC principle)

obviously, to use these goals, you need to use a state template (I'm not sure).

But when reading another code, I often come across an enumeration of just a non-state template. Does it have a status template?

+4
source share
2 answers

Why do we use the state template? To remove duplication of conditional logic and replace conditional code with polymorphism.

When do we have conditional duplication of logic? When we have many actions that depend on state, you should duplicate your conditional logic in each action. It becomes very annoying when you have many conditions. Also, code duplication means that you must update each copy of the duplicated code as you add new states.

So, if I don't have duplicate conditional logic, I would rather go with enum-based state instead of creating a new class hierarchy with many classes for states. Sometimes I even prefer duplicating conditional logic: for example. when I have many conditions, but only a few state-dependent actions. In this case, I prefer to have two switch blocks instead of creating ten new classes.

+8
source

Typically, the ENUM approach includes some table (array) of states and transitions. While the design pattern provides the same with objects.

If you mean the approach to a table with ENUM, then for the solution you will need to use a large if / else if block, which is completely uncontrollable. Turning to the section below, I think it is clear that this particular solution is inferior.

This is what I would call PROs and CONs of each

ENUM table

PROs:

  • It’s easier to see all the states and transitions, since the table is defined in one place.

Disadvantages:

  • States and transitions are more hard-coded, and more code changes are required to extend

Design Pattern

PROs:

  • It is easier to renew new states by adding a new object. (Principle of opening / closing)
  • It is easier to guarantee that all signals are processed by states, since the base class must define the signals as abstract functions.
  • It is easier to extend the behavior of individual states by taking them out of state. A state template must put a specific state in one object.

Disadvantages:

  • It’s harder to see all the states and their relationships while looking at the code, because they are distributed between several different classes.
  • May result in an unmanageable number of objects. But compare this with the corresponding if / else blocks needed for the corresponding ENUM solution.
+11
source

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


All Articles