TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

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

6 pointsby atomlib26 days ago

4 comments

karmakaze26 days ago
This is a bad example. All it did was move the implementation of multiple behaviors (calls, messages, alarms, notifications) into each of the state instances.<p>A better way to handle this is to separate policy and mechanism. The state has configuration about handling of (calls, messages, alarms, notifications), and when each thing needs to be done that call&#x2F;message&#x2F;etc config is requested from the state and processed uniformly from there on out, not by the phone nor the state but by the call&#x2F;message&#x2F;etc handler.
mog_dev26 days ago
Turning if statements into a collection of classes requires a bit more thoughts than &quot;Stop Writing If-Else Trees&quot;<p>Sometimes the State pattern transforms &quot;one big if-else tree&quot; into &quot;a forest of tiny classes&quot; with its own complexity tax. Good design isn&#x27;t about eliminating conditionals — it&#x27;s about putting them where they make the most sense.<p>The real skill is knowing when your state transitions are complex enough to warrant the abstraction overhead.
评论 #43785686 未加载
cadamsdotcom26 days ago
This is a domain modeling question.<p>If your if-else branches and flags are creating a combinatorial explosion and&#x2F;or allowing more states to exist than are valid, pay the complexity tax of introducing a State pattern - it will pay itself back in maintainability and lack of bugs over time.<p>But if you’re just talking about one or two standalone values, the state is already there, represented as simply as possible by your enums.
7e26 days ago
Most of the time the state pattern obfuscates logic and makes the entire thing much harder to understand.