From time to time it's need to make support for states for objects. As I understand there are two approaches:
- ENUM (SIMPLE)
- 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?
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.