Vincent Vauban’s Post

🛡️🧩 GUARDED PATTERNS WITH WHEN IN JAVA (JDK 21+) 🔸 TLDR Guarded patterns let you add a boolean condition to a pattern case using when, so you can express type + rule in one place inside a switch. Cleaner than nested if chains ✅ 🔸 THE PROBLEM (JAVA 8 STYLE) You match the type… then you nest another if for the condition. It works, but it gets noisy fast 😵💫 if (shape instanceof Circle c) { if (c.radius() > 10) { return "large circle"; } else { return "small circle"; } } else { return "not a circle"; } 🔸 THE MODERN WAY (JAVA 21+) Same logic, but expressed declaratively: “if it’s a Circle and radius > 10…” 🎯 return switch (shape) { case Circle c when c.radius() > 10 -> "large circle"; case Circle c -> "small circle"; default -> "not a circle"; }; 🔸 WHY WHEN IS A BIG WIN ▪️ 🎯 PRECISE MATCHING — Type + condition in a single case label ▪️ 📐 FLAT STRUCTURE — No nested branching inside a case ▪️ 📖 READABLE INTENT — Reads almost like English (“case Circle when radius > 10”) ▪️ 🧼 EASIER TO EXTEND — Add more guarded cases without turning code into a maze 🔸 TAKEAWAYS ▪️ ✅ Use when to refine a pattern match with a boolean condition ▪️ ✅ Prefer guarded cases over “case + nested if” for readability ▪️ ✅ Great fit for classification logic (rules, routing, categorization) ▪️ ⚠️ Order matters: the first matching case wins, so put more specific guards first #Java #Java21 #PatternMatching #SwitchExpression #CleanCode #Refactoring #SoftwareEngineering #JVM Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap src: https://lnkd.in/gKmcDm3h

  • Guarded patterns

To view or add a comment, sign in

Explore content categories