Learn how to simplify your Java code by replacing complex if-else statements with the Strategy Pattern. This blog provides a concise guide with practical code examples for cleaner and more maintainable code.
When your Java code is cluttered with multiple if-else statements based on input conditions, it becomes hard to maintain and extend. The Strategy Pattern offers a clean solution by encapsulating algorithms into separate classes, allowing you to select the appropriate behavior at runtime.
<TechStack technologies={["Java", "Design Patterns", "OOP", "Clean Code"]} />
<Callout type="info"> The Strategy Pattern is one of the most practical design patterns for eliminating complex conditional logic and making your code more maintainable. </Callout>public void processInput(String input) {
if ("ADD".equals(input)) {
// Perform addition
} else if ("SUBTRACT".equals(input)) {
// Perform subtraction
} else if ("MULTIPLY".equals(input)) {
// Perform multiplication
} else {
// Default action
}
}
public interface OperationStrategy {
void execute(int a, int b);
}
public class AdditionStrategy implements OperationStrategy {
@Override
public void execute(int a, int b) {
System.out.println("Sum: " + (a + b));
}
}
public class SubtractionStrategy implements OperationStrategy {
@Override
public void execute(int a, int b) {
System.out.println("Difference: " + (a - b));
}
}
public class MultiplicationStrategy implements OperationStrategy {
@Override
public void execute(int a, int b) {
System.out.println("Product: " + (a * b));
}
}
import java.util.HashMap;
import java.util.Map;
public class OperationContext {
private static final Map<String, OperationStrategy> strategies = new HashMap<>();
static {
strategies.put("ADD", new AdditionStrategy());
strategies.put("SUBTRACT", new SubtractionStrategy());
strategies.put("MULTIPLY", new MultiplicationStrategy());
}
public static void executeStrategy(String operation, int a, int b) {
OperationStrategy strategy = strategies.getOrDefault(operation, (x, y) -> {
System.out.println("Invalid operation");
});
strategy.execute(a, b);
}
}
public void processInput(String operation, int a, int b) {
OperationContext.executeStrategy(operation, a, b);
}
By replacing multiple if-else statements with the Strategy Pattern, your code becomes more organized and scalable, adhering to solid design principles. This approach not only simplifies the addition of new functionalities but also makes your codebase easier to understand and maintain.
If you found this article helpful and would like to discuss how these concepts can be applied to your project, I'd love to hear from you.