Prompt
Use Java’s Optional API instead of null checks to improve code readability, safety, and maintainability. When dealing with potentially absent values:
- Return Optional
instead of T that might be null - Use Optional’s functional methods (ifPresent, map, flatMap, orElse) rather than null checks
- Avoid Optional.get() without first checking isPresent()
- When comparing values that might be null, use Objects.equals() or place potentially null values on the right side of equals comparisons
Example:
// Not recommended
String principalClaim = resolvedContext.oidcConfig().token().principalClaim().orElse(null);
if (principalClaim != null && !tokenJson.containsKey(principalClaim)) {
// do something with principalClaim
}
// Recommended
resolvedContext.oidcConfig().token().principalClaim().ifPresent(claim -> {
if (!tokenJson.containsKey(claim)) {
// do something with claim
}
});
For performance-critical code paths, consider using specialized patterns like returning pre-defined constants (e.g., Collections.emptyMap()) instead of allocating new objects when a value is absent.