Member-only story
🚫 Stop Writing Repetitive Conditions: Try Pattern Matching Instead (Java 21+)
In traditional Java, it’s common to see repetitive instanceof
checks and type casts scattered throughout conditional logic. While this might work, it leads to verbose code, fragile logic, and poor readability.
With Java 21, pattern matching has become a first-class feature — allowing you to cleanly match object types, extract values, and make decisions without repetition.
In this article, we’ll show how to refactor repetitive conditional logic using Java 21’s pattern matching for instanceof
and switch
— with practical examples to help you write cleaner, more expressive code.
Let’s get started!
🤯 The Problem: Repetitive Type Checks and Casting
Here’s a common code pattern many Java developers write:
public void printValue(Object obj) {
if (obj instanceof String) {
String s = (String) obj;
System.out.println("String: " + s.toUpperCase());
} else if (obj instanceof Integer) {
Integer i = (Integer) obj;
System.out.println("Double: " + (i * 2));
} else if (obj instanceof List) {
List<?> list = (List<?>) obj;
System.out.println("List size: " + list.size());
}
}
Problems with this style:
- Repeats type checks and casts
- Harder to maintain
- Cluttered with boilerplate