Java is often criticized for verbosity, but modern Java can be concise. Here’s how to write cleaner code.
Modern Java Features
Records (Java 14+)
// Old way
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getters, equals, hashCode, toString...
}
// New way
public record User(String name, String email) { }
Pattern Matching (Java 17+)
// Old way
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
// New way
if (obj instanceof String s) {
System.out.println(s.length());
}
Switch Expressions (Java 14+)
// Old way
String result;
switch (day) {
case MONDAY:
case FRIDAY:
result = "Weekday";
break;
default:
result = "Weekend";
}
// New way
String result = switch (day) {
case MONDAY, FRIDAY -> "Weekday";
default -> "Weekend";
};
Best Practices
Use Streams
// Old way
List<String> filtered = new ArrayList<>();
for (String name : names) {
if (name.startsWith("J")) {
filtered.add(name.toUpperCase());
}
}
// New way
List<String> filtered = names.stream()
.filter(name -> name.startsWith("J"))
.map(String::toUpperCase)
.toList();
Use Optional
// Old way
String result = null;
if (user != null && user.getName() != null) {
result = user.getName().toUpperCase();
}
// New way
String result = Optional.ofNullable(user)
.map(User::getName)
.map(String::toUpperCase)
.orElse(null);
Conclusion
Modern Java is concise when you:
- Use records for data classes
- Use pattern matching
- Use streams for collections
- Use Optional for null handling
- Follow best practices
Write concise, modern Java! ☕