Stop Writing If-Else Trees: Use the State Pattern Instead

Jane Smith
|
May 26, 2025

A Real-World Analogy: Phone Notification Modes

Imagine you have a smartphone with multiple notification modes: Normal, Vibrate, and Silent. In Normal mode, incoming calls ring out loud. In Vibrate mode, the phone doesn’t ring but buzzes. In Silent mode, it neither rings nor vibrates — perhaps it just logs a missed call. You (the phone’s owner) might manually switch between these modes depending on context (at work, in a meeting, at the movies, etc.), and the phone’s behavior changes accordingly without you fiddling with the internals of how ringing works each time.

This scenario is a relatable analogy for the State pattern:

The Phone is the object whose behavior changes.

The current mode (Normal/Vibrate/Silent) is the internal state of the phone.

Each state defines how the phone should behave for certain actions (like receiving a call).

Switching modes is like changing the internal state object, which in turn changes the phone’s behavior.

Why not just use an if-else or enum? You could code the phone’s behavior with a simple if or switch:

WRITTEN BY
Jane Smith
Jane Smith is a passionate writer and educator. She specializes in children's literature and has published several award-winning books that inspire young readers to explore their imagination.
_____________________________________________________________________
Join the conversation
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.