Urgent.News

What's breaking now, across thousands of outlets.

Tech

The State Pattern Trap: Why GoF Is Not Always the Best Choice

Have you ever tried to use the classic Gang of Four (GoF) State Pattern in real code? You might have hit a wall. You might have thought, "Wait, this feels way too connected." You are not wrong about that. In school and many engineering interviews, the GoF State Pattern looks great. It promises to fix big, ugly switch statements. But real business rules are hard. When you use this pattern in real…

When you attempt to employ the classic Gang of Four (GoF) State Pattern in practical code, you may encounter challenges. You might feel that it feels overly interconnected. This perception is accurate. In academic settings and numerous engineering interviews, the GoF State Pattern appears impressive, offering a solution to complex switch statements.

However, when implemented in real-world business scenarios, it can rapidly deteriorate into an unwieldy mess. Each state becomes overly aware of other states. To understand why, we will compare the GoF pattern with a Finite State Machine (FSM). We will also determine when to employ each approach.

The allure of the GoF State Pattern lies in its promise to simplify code. The primary object delegates its tasks to state objects. However, there is a caveat. The state classes must initiate the transition to the subsequent state. Consider a straightforward traffic light example. It alternates between Red, Green, and Yellow states perpetually.

The RedState class handles the transition to GreenState. This tight coupling is manageable for a simple traffic light system with unchanging rules. But what happens when business rules undergo modifications? Suppose the city council introduces a new regulation: during nighttime (midnight to 5:00 AM), the light must emit a flashing yellow.

In this case, you must modify both the RedState and YellowState classes to incorporate new time checks. Additionally, you may need to introduce a new flashing state. As the number of states increases, the codebase becomes increasingly convoluted.

In contrast, the Finite State Machine (FSM) emerges as a more suitable solution in the real world. Real-life scenarios often involve non-linear transitions. An online order does not simply progress from Pending to Shipped to Delivered. It can also transition to Cancelled or be returned to the sender. If you adopt the GoF approach in such scenarios, the PendingState class must be aware of multiple other states, leading to excessive complexity.

This is where the FSM shines. The core idea behind FSM is central control. State classes become streamlined, focusing solely on the rules governing behavior within that specific state. A central controller, known as an Orchestrator, manages the transitions between states. Let us illustrate this with an Order Processing example. We define an orderRules object outlining the permissible transitions between states.

Next, we create an OrderController class responsible for handling events and updating the current state accordingly. This centralized approach eliminates the need for state classes to be intimately intertwined with one another.

The FSM offers several advantages over the GoF State Pattern. Firstly, it prevents states from knowing about each other, reducing unnecessary dependencies. Secondly, clear state rules are established in a single, easily comprehensible list. Thirdly, adding a new state does not disrupt existing code; you simply update the rules list.

When deciding between the two approaches, consider the complexity and flexibility of your system. Use the GoF State Pattern when the flow remains consistent and predictable, such as in a traffic light system with a fixed sequence of states. Conversely, opt for a Central FSM when dealing with intricate rules that allow for non-linear transitions, such as online order processing or game AI.

External events, like user interactions or timers, often dictate state changes in these scenarios. Additionally, the FSM facilitates code readability and maintainability, making it easier to trace the sequence of state transitions. Remember, while the GoF State Pattern serves as an excellent educational tool and works well for simple problems, a central FSM is a more robust solution for complex real-world software systems.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Wednesday 26 August →