Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

State pattern vs ENUM

From time to time it's need to make support for states for objects. As I understand there are two approaches:

  1. ENUM (SIMPLE)
  2. STATE pattern (OC principle)

it's evident that need to use State pattern for such purposes(I am not sure).

But reading other code I often face with enum only not state pattern at all. Does state pattern has power?

like image 247
user1074896 Avatar asked May 25 '12 09:05

user1074896


People also ask

What are the disadvantages of State pattern?

Disadvantages. The State pattern requires a lot of code to be written. Depending on how many different state transition methods are defined, and how many possible states an object can be in, there can quickly be dozens or more different methods that must be written.

Is enum a design pattern?

Singleton Design Pattern is one of GOF (Gang of Four) design pattern. It comes under creational patterns. The main idea behind the Singleton is, create only one object of a specific class is ever created.

What is the purpose of State pattern?

The state pattern is used in computer programming to encapsulate varying behavior for the same object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.

When should a developer use the State pattern?

State design pattern is one of the behavioral design pattern. State design pattern is used when an Object change its behavior based on its internal state.


1 Answers

Why do we use State pattern? To remove conditional logic duplication, and replace conditional code with polymorphism.

When do we have conditional logic duplication? When we have many actions, which depend on state, thus you have to duplicate your conditional logic in every action. It becomes very annoying when you have many states. Also code duplication means that you should update every copy of duplicated code when you are adding new states.

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

like image 153
Sergey Berezovskiy Avatar answered Oct 07 '22 14:10

Sergey Berezovskiy