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")) {…