optional: java.util.Optional module (factories, extraction, orElse vs orElseGet, anti-patterns, Stream interop, JSpecify contrast)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6gdUKYmBw6bUKcM7t
This commit is contained in:
Ankur
2026-11-25 22:58:57 +05:30
co-authored by Claude Sonnet 5.5
parent cca173d104
commit 47e4ccbefa
25 changed files with 793 additions and 0 deletions
@@ -0,0 +1,106 @@
package com.ankurm.optional;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/** Each misuse is run for real, so the failure you read about is the failure you can reproduce. */
public class AntiPatternsDemo {
// 1. Optional as a field of a Serializable class.
static class BadCustomer implements Serializable {
String name = "Ankur";
Optional<String> email = Optional.of("[email protected]");
}
// The alternative: store the plain (possibly null) value, expose an Optional.
static class GoodCustomer implements Serializable {
String name = "Ankur";
private String email = "[email protected]"; // may be null
Optional<String> getEmail() {
return Optional.ofNullable(email);
}
}
static void serialize(Object o) throws IOException {
try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {
out.writeObject(o);
}
}
// 2. Optional as a parameter: the caller can still pass null.
static String greet(Optional<String> name) {
return "Hello, " + name.orElse("guest");
}
// 3. A method that returns Optional but hands back null.
static Optional<String> brokenLookup() {
return null;
}
static Optional<String> correctLookup() {
return Optional.empty();
}
// 4. Optional wrapping a collection.
static Optional<List<String>> ordersOptional() {
return Optional.of(List.of());
}
static List<String> ordersList() {
return List.of();
}
public static void main(String[] args) throws Exception {
// isPresent + get versus a single expression
Optional<String> nick = Optional.of("ankur");
String viaGet = nick.isPresent() ? nick.get().toUpperCase() : "GUEST";
String viaMap = nick.map(String::toUpperCase).orElse("GUEST");
System.out.println("1 isPresent+get : " + viaGet + " | map+orElse : " + viaMap);
// Optional field
try {
serialize(new BadCustomer());
} catch (IOException e) {
System.out.println("2 Optional field : " + e.getClass().getName() + ": " + e.getMessage());
}
serialize(new GoodCustomer());
System.out.println("2 nullable field : serialized OK, getEmail() = " + new GoodCustomer().getEmail());
// Optional parameter
System.out.println("3 greet(empty) : " + greet(Optional.empty()));
try {
greet(null);
} catch (NullPointerException e) {
System.out.println("3 greet(null) : NullPointerException, " + e.getMessage());
}
// Returning null from an Optional method
try {
brokenLookup().map(String::length).orElse(0);
} catch (NullPointerException e) {
System.out.println("4 return null : NullPointerException, " + e.getMessage());
}
System.out.println("4 return empty() : " + correctLookup().map(String::length).orElse(0));
// Optional.of on a value that can be null
Map<String, String> config = new HashMap<>();
try {
Optional.of(config.get("timeout"));
} catch (NullPointerException e) {
System.out.println("5 of(map.get(..)) : NullPointerException (use ofNullable)");
}
System.out.println("5 ofNullable : " + Optional.ofNullable(config.get("timeout")));
// Collections
System.out.println("6 Optional<List> : empty list wrapped = " + ordersOptional()
+ " | plain list = " + ordersList());
System.out.println("6 states : Optional<List> has 3 (empty, present-empty, present-full), List has 2");
}
}
@@ -0,0 +1,33 @@
package com.ankurm.optional;
import java.util.Optional;
/** The three factory methods, and what each does with null. */
public class CreationDemo {
public static void main(String[] args) {
// 1. empty(): a known absence.
Optional<String> emptyUsername = Optional.empty();
System.out.println("empty : " + emptyUsername);
// 2. of(value): the value must not be null. null is a programming error here.
Optional<String> presentUsername = Optional.of("ankur");
System.out.println("of : " + presentUsername);
// 3. ofNullable(value): for values you do not control (DB rows, HTTP, System properties).
String rawValue = System.getProperty("user.nickname"); // null unless -Duser.nickname is set
Optional<String> safeUsername = Optional.ofNullable(rawValue);
System.out.println("ofNullable : " + safeUsername);
// of(null) fails immediately, at the call site that made the mistake.
try {
Optional.of(rawValue);
} catch (NullPointerException e) {
System.out.println("of(null) : " + e.getClass().getName() + ", message=" + e.getMessage());
}
// Optional values compare by content.
System.out.println("equals : " + Optional.of("a").equals(Optional.of("a")));
System.out.println("empty==empty : " + (Optional.empty() == Optional.empty()));
}
}
@@ -0,0 +1,50 @@
package com.ankurm.optional;
import java.util.NoSuchElementException;
import java.util.Optional;
/** Every way to get a value out, from unsafe to safe. */
public class ExtractionDemo {
public static void main(String[] args) {
Optional<String> city = Optional.of("Mumbai");
Optional<String> noCity = Optional.empty();
System.out.println("isPresent : " + city.isPresent());
System.out.println("isEmpty : " + noCity.isEmpty()); // Java 11+
// get(): works when present, throws when empty.
System.out.println("get (present): " + city.get());
try {
noCity.get();
} catch (NoSuchElementException e) {
System.out.println("get (empty) : " + e.getClass().getName() + ": " + e.getMessage());
}
// The no-argument orElseThrow() (Java 10+) is the same behaviour with an honest name.
try {
noCity.orElseThrow();
} catch (NoSuchElementException e) {
System.out.println("orElseThrow(): " + e.getClass().getName() + ": " + e.getMessage());
}
// Defaults and domain exceptions.
System.out.println("orElse : " + noCity.orElse("Unknown City"));
System.out.println("orElseGet : " + noCity.orElseGet(ExtractionDemo::fetchDefaultCity));
try {
noCity.orElseThrow(() -> new IllegalStateException("City must be set"));
} catch (IllegalStateException e) {
System.out.println("orElseThrow(s): " + e.getClass().getName() + ": " + e.getMessage());
}
// Side effects.
city.ifPresent(c -> System.out.println("ifPresent : City is " + c));
noCity.ifPresentOrElse(
c -> System.out.println("ifPresentOrElse: City found " + c),
() -> System.out.println("ifPresentOrElse: No city configured"));
}
private static String fetchDefaultCity() {
return "DefaultCity";
}
}
@@ -0,0 +1,54 @@
package com.ankurm.optional;
import java.lang.annotation.Target;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
/**
* Optional and JSpecify answer different questions. Optional is a runtime value for a method result.
* JSpecify is a compile-time contract on any type, and it is only enforced when a checker runs.
*/
public class NullableContrastDemo {
static class Account {
private final String id;
private final @Nullable String nickname; // a field: use the annotation, not Optional
Account(String id, @Nullable String nickname) {
this.id = id;
this.nickname = nickname;
}
// A return value that may be absent: Optional is the better signal for a caller.
Optional<String> nickname() {
return Optional.ofNullable(nickname);
}
// The same fact expressed as an annotation instead.
@Nullable String rawNickname() {
return nickname;
}
String display() {
return nickname().orElse(id);
}
}
static String describe(@Nullable String s) {
return s == null ? "no value" : s.toUpperCase();
}
public static void main(String[] args) {
Account a = new Account("acc-1", null);
Account b = new Account("acc-2", "Ankur");
System.out.println("display (null nickname) : " + a.display());
System.out.println("display (set nickname) : " + b.display());
System.out.println("rawNickname : " + a.rawNickname());
System.out.println("describe(null) : " + describe(null));
Target t = Nullable.class.getAnnotation(Target.class);
System.out.println("@Nullable targets : " + java.util.Arrays.toString(t.value()));
System.out.println("package is @NullMarked : "
+ (NullableContrastDemo.class.getPackage().getAnnotation(org.jspecify.annotations.NullMarked.class) != null));
}
}
@@ -0,0 +1,68 @@
package com.ankurm.optional;
import java.util.Optional;
/** orElse(x) builds x before the call; orElseGet(supplier) builds it only when needed. */
public class OrElseVsOrElseGetDemo {
static int built = 0;
static String expensiveDefault() {
built++;
return "default";
}
static String failingDefault() {
throw new IllegalStateException("default lookup failed");
}
static String slowDefault() {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "default";
}
public static void main(String[] args) {
Optional<String> present = Optional.of("cached");
Optional<String> empty = Optional.empty();
built = 0;
present.orElse(expensiveDefault());
System.out.println("orElse on PRESENT : default built " + built + " time(s)");
built = 0;
present.orElseGet(OrElseVsOrElseGetDemo::expensiveDefault);
System.out.println("orElseGet on PRESENT : default built " + built + " time(s)");
built = 0;
empty.orElse(expensiveDefault());
System.out.println("orElse on EMPTY : default built " + built + " time(s)");
built = 0;
empty.orElseGet(OrElseVsOrElseGetDemo::expensiveDefault);
System.out.println("orElseGet on EMPTY : default built " + built + " time(s)");
// The sharper trap: a default that throws breaks orElse even when a value is present.
try {
present.orElse(failingDefault());
} catch (IllegalStateException e) {
System.out.println("orElse on PRESENT with failing default : threw " + e.getMessage());
}
System.out.println("orElseGet on PRESENT with failing default : " + present.orElseGet(OrElseVsOrElseGetDemo::failingDefault));
// Cost, indicative only: 200 calls, default takes at least 5 ms to build.
long t0 = System.nanoTime();
for (int i = 0; i < 200; i++) present.orElse(slowDefault());
long orElseMs = (System.nanoTime() - t0) / 1_000_000;
t0 = System.nanoTime();
for (int i = 0; i < 200; i++) present.orElseGet(OrElseVsOrElseGetDemo::slowDefault);
long orElseGetMs = (System.nanoTime() - t0) / 1_000_000;
System.out.println("200 calls, slow default (indicative): orElse >= 1000 ms: " + (orElseMs >= 1000)
+ ", orElseGet < 100 ms: " + (orElseGetMs < 100));
}
}
@@ -0,0 +1,60 @@
package com.ankurm.optional;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/** The canonical use: a lookup that may not find anything. Three ways a caller can react. */
public class RepositoryDemo {
record Product(int id, String name, double price) {}
static class ProductRepository {
private final Map<Integer, Product> store = new HashMap<>();
ProductRepository() {
store.put(1, new Product(1, "Laptop", 79999.0));
store.put(2, new Product(2, "Phone", 29999.0));
}
Optional<Product> findById(int productId) {
return Optional.ofNullable(store.get(productId));
}
}
static class ProductService {
private final ProductRepository repository = new ProductRepository();
// Pattern 1: hand the Optional to the caller; they decide what "missing" means.
Optional<Product> getProduct(int productId) {
return repository.findById(productId);
}
// Pattern 2: absence is an error.
Product requireProduct(int productId) {
return repository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("Product " + productId + " not found"));
}
// Pattern 3: transform, then default.
String getFormattedPrice(int productId) {
return repository.findById(productId)
.map(p -> String.format("%s - Rs %.2f", p.name(), p.price()))
.orElse("Product not available");
}
}
public static void main(String[] args) {
ProductService service = new ProductService();
service.getProduct(1).ifPresent(p -> System.out.println("Found : " + p.name()));
System.out.println("Required : " + service.requireProduct(1).name());
System.out.println(service.getFormattedPrice(2));
System.out.println(service.getFormattedPrice(99));
try {
service.requireProduct(99);
} catch (IllegalArgumentException e) {
System.out.println("Missing : " + e.getMessage());
}
}
}
@@ -0,0 +1,53 @@
package com.ankurm.optional;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/** Optional.stream(), Optional-returning terminal operations, primitive Optionals and lazy or(). */
public class StreamInteropDemo {
static Optional<String> lookup(String source, String result) {
System.out.println(" consulted " + source);
return Optional.ofNullable(result);
}
public static void main(String[] args) {
List<Optional<String>> raw = List.of(Optional.of("a"), Optional.empty(), Optional.of("c"), Optional.empty());
// Two ways to keep only the present values.
List<String> old = raw.stream().filter(Optional::isPresent).map(Optional::get).toList();
List<String> modern = raw.stream().flatMap(Optional::stream).toList();
System.out.println("filter+get : " + old);
System.out.println("flatMap(::stream) : " + modern);
System.out.println("stream sizes : present=" + Optional.of("x").stream().count()
+ " empty=" + Optional.empty().stream().count());
// Terminal operations that return Optional.
System.out.println("findFirst hit : " + Stream.of(3, 8, 12).filter(n -> n > 5).findFirst());
System.out.println("findFirst miss : " + Stream.of(3, 8, 12).filter(n -> n > 50).findFirst());
System.out.println("max : " + Stream.of("pune", "mumbai", "nashik").max(String::compareTo));
// Primitive specialisations: no boxing, different method names.
OptionalInt maxInt = IntStream.of(3, 9, 4).max();
OptionalDouble avg = IntStream.empty().average();
System.out.println("OptionalInt : " + maxInt + " getAsInt=" + maxInt.getAsInt());
System.out.println("OptionalDouble : " + avg + " orElse(-1)=" + avg.orElse(-1));
// or(): a lazy chain of fallbacks. Later sources are not consulted once one answers.
System.out.println("or() chain, cache hits:");
Optional<String> hit = lookup("cache", "from-cache")
.or(() -> lookup("database", "from-db"))
.or(() -> lookup("config", "from-config"));
System.out.println(" result = " + hit);
System.out.println("or() chain, cache and db miss:");
Optional<String> miss = lookup("cache", null)
.or(() -> lookup("database", null))
.or(() -> lookup("config", "from-config"));
System.out.println(" result = " + miss);
}
}
@@ -0,0 +1,41 @@
package com.ankurm.optional;
import java.util.Optional;
/** map, flatMap, filter and or on a small domain model. */
public class TransformDemo {
record Address(String city, String pincode) {}
record User(String name, Address address) {}
public static void main(String[] args) {
Optional<User> userWithAddress = Optional.of(new User("Ankur", new Address("Pune", "411001")));
Optional<User> userWithoutAddress = Optional.of(new User("Alex", null));
// map: transform the value; an empty Optional stays empty and the function is never called.
Optional<String> userName = userWithAddress.map(User::name);
System.out.println("name : " + userName.orElse("N/A"));
Optional<String> pincode = userWithAddress.map(User::address).map(Address::pincode);
System.out.println("pincode : " + pincode.orElse("N/A"));
// A function that returns null turns into an empty Optional, not an NPE.
Optional<String> missingPin = userWithoutAddress.map(User::address).map(Address::pincode);
System.out.println("missing pin : " + missingPin.orElse("N/A"));
System.out.println("map to null : " + Optional.of("x").map(s -> (String) null));
// map vs flatMap when the function itself returns an Optional.
Optional<Optional<Address>> nested = userWithAddress.map(u -> Optional.ofNullable(u.address()));
Optional<Address> flat = userWithAddress.flatMap(u -> Optional.ofNullable(u.address()));
System.out.println("map nests : " + nested);
System.out.println("flatMap flat : " + flat);
System.out.println("flatMap city : " + flat.map(Address::city).orElse("N/A"));
// filter: keep the value only if the predicate holds.
System.out.println("filter match : " + pincode.filter(p -> p.startsWith("411")).orElse("not 411xx"));
System.out.println("filter miss : " + pincode.filter(p -> p.startsWith("400")).orElse("not 400xx"));
// or (Java 9+): fall back to another Optional, evaluated lazily.
System.out.println("or fallback : " + missingPin.or(() -> Optional.of("110001")).orElse("?"));
}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.ankurm.optional;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,106 @@
package com.ankurm.optional;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
/** Pins every behavioural claim the article makes. */
class OptionalContractTest {
@Test
void ofNullThrowsButOfNullableDoesNot() {
assertThrows(NullPointerException.class, () -> Optional.of(null));
assertEquals(Optional.empty(), Optional.ofNullable(null));
}
@Test
void getOnEmptyThrowsNoSuchElement() {
NoSuchElementException e = assertThrows(NoSuchElementException.class, () -> Optional.empty().get());
assertEquals("No value present", e.getMessage());
}
@Test
void orElseIsEagerAndOrElseGetIsLazy() {
Optional<String> present = Optional.of("v");
AtomicInteger eager = new AtomicInteger();
AtomicInteger lazy = new AtomicInteger();
present.orElse(build(eager));
present.orElseGet(() -> build(lazy));
assertEquals(1, eager.get());
assertEquals(0, lazy.get());
}
@Test
void orElseWithFailingDefaultThrowsEvenWhenPresent() {
Optional<String> present = Optional.of("v");
assertThrows(IllegalStateException.class, () -> present.orElse(fail()));
assertEquals("v", present.orElseGet(OptionalContractTest::fail));
}
@Test
void mapReturningNullBecomesEmpty() {
assertEquals(Optional.empty(), Optional.of("x").map(s -> (String) null));
}
@Test
void mapNestsAndFlatMapFlattens() {
Optional<Optional<String>> nested = Optional.of("x").map(Optional::of);
Optional<String> flat = Optional.of("x").flatMap(Optional::of);
assertEquals(Optional.of(Optional.of("x")), nested);
assertEquals(Optional.of("x"), flat);
}
@Test
void orIsLazy() {
AtomicInteger consulted = new AtomicInteger();
Optional<String> r = Optional.of("a").or(() -> {
consulted.incrementAndGet();
return Optional.of("b");
});
assertEquals("a", r.orElseThrow());
assertEquals(0, consulted.get());
}
@Test
void flatMapStreamDropsEmpties() {
List<Optional<String>> raw = List.of(Optional.of("a"), Optional.empty(), Optional.of("c"));
assertEquals(List.of("a", "c"), raw.stream().flatMap(Optional::stream).toList());
}
@Test
void optionalIsNotSerializable() {
NotSerializableException e = assertThrows(NotSerializableException.class, () -> {
try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {
out.writeObject(new Holder());
}
});
assertEquals("java.util.Optional", e.getMessage());
}
@Test
void returningNullFromAnOptionalMethodBlowsUpTheCaller() {
assertThrows(NullPointerException.class, () -> AntiPatternsDemo.brokenLookup().isPresent());
}
static class Holder implements java.io.Serializable {
Optional<String> value = Optional.of("x");
}
private static String build(AtomicInteger counter) {
counter.incrementAndGet();
return "default";
}
private static String fail() {
throw new IllegalStateException("boom");
}
}