Sitemap

Member-only story

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

11 min readJul 6, 2025

--

Press enter or click to view image in full size

Have you ever looked at your code and found a huge mess of if-else statements that just keeps growing? As your program gets bigger, these if-else trees become harder to read, test, and change. There’s a better way to handle this problem: the State Pattern.

What’s Wrong With If-Else Trees?

Before we talk about the solution, let’s look at the problem. Here’s an example of code that uses many if-else statements to handle different states of a document:

public class Document {
private String state = "DRAFT";

public void publish() {
if (state.equals("DRAFT")) {
state = "PUBLISHED";
System.out.println("Document published successfully!");
} else if (state.equals("PUBLISHED")) {
System.out.println("Document is already published!");
} else if (state.equals("ARCHIVED")) {
System.out.println("Cannot publish an archived document!");
}
}

public void archive() {
if (state.equals("DRAFT")) {
System.out.println("Cannot archive a draft document!");
} else if (state.equals("PUBLISHED")) {
state = "ARCHIVED";
System.out.println("Document archived successfully!");
} else if (state.equals("ARCHIVED")) {…

--

--

Naveen Metta
Naveen Metta

Written by Naveen Metta

I'm a Full Stack Developer with 4+ years of experience. feel free to reach out for any help : mettanaveen701@gmail.com