Java 8: Replace nested null checks with Optional. Show the alternatives and the anti-patterns.
Problem
user.getAddress().getCity() can fail with NullPointerException at any level. Return the city of a user's address in upper case, or "UNKNOWN".
import java.util.Optional;
final class Address {
private final String city;
Address(String city) { this.city = city; }
String getCity() { return city; }
}
final class User {
private final Address address;
User(Address address) { this.address = address; }
Address getAddress() { return address; } // may return null (legacy API)
Optional<Address> address() { return Optional.ofNullable(address); } // Optional-returning API
}Approach 1: Nested null checks (Java 7)
Correct but deeply nested ("arrow code") and easy to forget one level.
class CityNested {
static String city(User user) {
if (user != null) {
Address a = user.getAddress();
if (a != null) {
String c = a.getCity();
if (c != null && !c.isEmpty()) return c.toUpperCase();
}
}
return "UNKNOWN";
}
}Approach 2: Guard clauses (flat imperative code)
Early returns flatten the logic. Perfectly fine code, still manual.
class CityGuards {
static String city(User user) {
if (user == null || user.getAddress() == null) return "UNKNOWN";
String c = user.getAddress().getCity();
return c == null || c.isEmpty() ? "UNKNOWN" : c.toUpperCase();
}
}Approach 3: Optional chain with map (Java 8)
Each map runs only if a value is present; a null result becomes an empty Optional, so the chain short-circuits safely.
import java.util.Optional;
class CityOptional {
static String city(User user) {
return Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.filter(c -> !c.isEmpty())
.map(String::toUpperCase)
.orElse("UNKNOWN");
}
}Approach 4: Design APIs to return Optional and use flatMap (best)
When getters already return Optional, chain them with flatMap (otherwise you get Optional<Optional<Address>>). Use orElseThrow when absence is a real error, and orElseGet for expensive defaults.
import java.util.Map;
import java.util.Optional;
class CityRepository {
private final Map<Long, User> users;
CityRepository(Map<Long, User> users) { this.users = users; }
Optional<User> findById(long id) { return Optional.ofNullable(users.get(id)); }
String cityOf(long userId) {
return findById(userId)
.flatMap(User::address)
.map(Address::getCity)
.map(String::toUpperCase)
.orElse("UNKNOWN");
}
String requiredCity(long userId) {
return findById(userId).flatMap(User::address).map(Address::getCity)
.orElseThrow(() -> new IllegalStateException("No city for user " + userId));
}
}Run all approaches
import java.util.HashMap;
import java.util.Map;
class CityDemo {
public static void main(String[] args) {
User full = new User(new Address("Pune")), noAddress = new User(null), noCity = new User(new Address(null));
for (User u : new User[] {full, noAddress, noCity, null}) {
System.out.println(CityNested.city(u) + " " + CityGuards.city(u) + " " + CityOptional.city(u));
}
Map<Long, User> db = new HashMap<>();
db.put(1L, full);
CityRepository repo = new CityRepository(db);
System.out.println(repo.cityOf(1) + " " + repo.cityOf(2)); // PUNE UNKNOWN
try { repo.requiredCity(2); } catch (IllegalStateException e) { System.out.println(e.getMessage()); }
}
}Anti-patterns to avoid
if (opt.isPresent()) return opt.get();: just a verbose null check; usemap/orElse.opt.get()without checking: throwsNoSuchElementException; preferorElseThrow()(Java 10) to make intent explicit.Optionalas a field, constructor or method parameter, or inside collections: it is designed as a return type, is notSerializable, and adds allocation.orElse(expensiveCall()): the argument is always evaluated; useorElseGet(() -> expensiveCall()).- Returning
nullfrom a method declared to returnOptional.
Feasible → optimal
All are O(1). Approach 3 is the idiomatic fix for legacy nullable getters; Approach 4 (Optional-returning APIs with flatMap) is the best design because absence becomes part of the type and callers cannot forget it.
Follow-up questions interviewers ask
Try answering each one before you open it.
What did Java 9 to 11 add to Optional?
Java 9: ifPresentOrElse(action, emptyAction), or(() -> otherOptional) for fallbacks that are themselves optional, and stream() (0 or 1 elements, handy for flatMap(Optional::stream) to drop empties from a stream). Java 10: no-argument orElseThrow() as a clearer alias of get(). Java 11: isEmpty().
Should a repository method return Optional<List<Order>>?
No. Return an empty list for "no results"; collections already have a natural empty value. Optional is for single values that may be absent, such as findById.