Optics Extensions: Validated Operations
Get a null field, or an update that can fail, back as a Maybe, Either, Validated or Try value.
- Read a field that may be
nullas aMaybe,EitherorValidatedwithgetMaybe,getEitherandgetValidated - Modify one field with a step that can fail, using
modifyEither,modifyMaybe,modifyTryorsetIfValid - Choose an all-or-nothing, first-error or accumulating bulk update:
modifyAllMaybe,modifyAllEitherormodifyAllValidated - Update only the elements that qualify with
modifyWherePossible, leaving the rest unchanged - Check a traversal without writing to it, using
countValidandcollectErrors
Traditional optics work brilliantly with clean, valid data. Real-world applications, however, deal with nullable fields, validation requirements, and operations that might throw exceptions. Optics Extensions bridge this gap by integrating lenses and traversals with Higher-Kinded-J's core types.
Each extension plays the part of a null check, or an if on a validation result, written once around a lens or traversal call. A null or a failed step comes back as a Maybe, Either, Validated or Try value. The extensions catch nothing themselves: for modifyTry, wrap the throwing call in Try.of, and its exception arrives as a Try failure.
Part 1: Lens Extensions
Importing Lens Extensions
import static org.higherkindedj.optics.extensions.LensExtensions.*;
These extension methods are also available through the Fluent API, which provides method chaining and a more discoverable interface.
Safe Access Methods
The examples in this part read an Affiliate, a partner paid a commission on the orders they refer. A newcomer's email, commission and bio may be null:
// A partner paid a commission, in percent, on the orders they refer. A newcomer may not yet have
// given an email, agreed a commission or written a bio, so those fields may be null.
@GenerateLenses
record Affiliate(String id, String name, String email, Integer commission, String bio) {}
Where an example reads affiliate, it is Alice, holding the id a1, the name Alice, the email alice@example.com, the commission 10 and the bio Lighting blogger.
getMaybe: Null-Safe Field Access
Returns Maybe.just(value) if the field is non-null, Maybe.nothing() otherwise.
Lens<Affiliate, String> bioLens = AffiliateLenses.bio();
Affiliate withBio = new Affiliate("a1", "Alice", "alice@example.com", 10, "Lighting blogger");
Maybe<String> bio = getMaybe(bioLens, withBio);
// Just(Lighting blogger)
Affiliate withoutBio = new Affiliate("a2", "Bob", "bob@example.com", 5, null);
Maybe<String> noBio = getMaybe(bioLens, withoutBio);
// Nothing
// Use with default
String displayBio = bio.orElse("No bio provided");
getEither: Access with Default Error
Returns Either.right(value) if non-null, Either.left(error) if null.
Lens<Affiliate, Integer> commissionLens = AffiliateLenses.commission();
Either<String, Integer> commission =
getEither(commissionLens, "Commission not agreed", affiliate);
// Right(10)
Affiliate newcomer = new Affiliate("a3", "Carol", "carol@example.com", null, null);
Either<String, Integer> noCommission =
getEither(commissionLens, "Commission not agreed", newcomer);
// Left(Commission not agreed)
String message = commission.fold(error -> "AppError: " + error, c -> "Commission: " + c + "%");
getValidated: Access with Validation Error
Like getEither, but returns Validated for consistency with validation workflows.
Lens<Affiliate, String> emailLens = AffiliateLenses.email();
Validated<String, String> email = getValidated(emailLens, "Email is required", affiliate);
// Valid(alice@example.com)
Affiliate noEmail = new Affiliate("a4", "Dan", null, 8, null);
Validated<String, String> missing = getValidated(emailLens, "Email is required", noEmail);
// Invalid(Email is required)
Modification Methods
modifyMaybe: Optional Modifications
Apply a modification that might not succeed. Returns Maybe.just(updated) if successful, Maybe.nothing() if it fails.
Lens<Affiliate, String> nameLens = AffiliateLenses.name();
Maybe<Affiliate> updated =
modifyMaybe(
nameLens,
name -> name.length() >= 2 ? Maybe.just(name.toUpperCase()) : Maybe.nothing(),
affiliate);
// Just(Affiliate[id=a1, name=ALICE, ...]); a name shorter than two letters gives Nothing
modifyEither: Fail-Fast Validation
Apply a modification with validation. Returns Either.right(updated) if valid, Either.left(error) if invalid.
Lens<Affiliate, Integer> commissionLens = AffiliateLenses.commission();
Either<String, Affiliate> updated = modifyEither(
commissionLens,
commission -> {
if (commission < 0) return Either.left("Commission cannot be negative");
if (commission > 50) return Either.left("Commission must be realistic");
return Either.right(commission + 1); // A raise!
},
affiliate
);
modifyTry: Exception-Safe Modifications
Apply a modification that might throw exceptions. Returns Try.success(updated) or Try.failure(exception).
Lens<Affiliate, String> emailLens = AffiliateLenses.email();
Try<Affiliate> updated = modifyTry(
emailLens,
email -> Try.of(() -> updateEmailInDatabase(email)),
affiliate
);
updated.match(
saved -> logger.info("Email updated: {}", saved.email()),
error -> logger.error("Update failed", error)
);
setIfValid: Conditional Updates
Set a new value only if it passes validation. Unlike modifyEither, you provide the new value directly.
Lens<Affiliate, String> nameLens = AffiliateLenses.name();
Either<String, Affiliate> updated = setIfValid(
nameLens,
name -> {
if (name.length() < 2) return Either.left("Name must be at least 2 characters");
if (!name.matches("[A-Z][a-z]+")) return Either.left("Name must start with capital letter");
return Either.right(name);
},
"Robert",
affiliate
);
Chaining Multiple Lens Updates
Lens<Affiliate, String> nameLens = AffiliateLenses.name();
Lens<Affiliate, String> emailLens = AffiliateLenses.email();
Either<String, Affiliate> capitalised = modifyEither(
nameLens,
name -> Either.right(capitalize(name)),
original
);
Either<String, Affiliate> result = capitalised.flatMap(named ->
modifyEither(
emailLens,
email -> Either.right(email.toLowerCase()),
named
)
);
Part 2: Traversal Extensions
Importing Traversal Extensions
import static org.higherkindedj.optics.extensions.TraversalExtensions.*;
Extraction Methods
Where an example in this part reads items, it is a list of two LineItems: SKU-1, one at 999.99, and SKU-2, two at 29.99. Where it reads orders, it is a list of the chapter's Orders in mixed statuses.
getAllMaybe: Extract All Values
Returns Maybe.just(values) if any elements exist, Maybe.nothing() for empty collections.
Lens<LineItem, BigDecimal> priceLens = LineItemLenses.price();
Traversal<List<LineItem>, BigDecimal> allPrices =
Traversals.<LineItem>forList().andThen(priceLens);
Maybe<List<BigDecimal>> prices = getAllMaybe(allPrices, items);
// Just([999.99, 29.99])
Maybe<List<BigDecimal>> noPrices = getAllMaybe(allPrices, List.of());
// Nothing
Bulk Modification Methods
modifyAllMaybe: All-or-Nothing Modifications
Returns Maybe.just(updated) if all modifications succeed, Maybe.nothing() if any fail. Atomic operation.
Function<BigDecimal, Maybe<BigDecimal>> raiseTenPercent =
price ->
price.compareTo(new BigDecimal("10")) >= 0
? Maybe.just(
price.multiply(new BigDecimal("1.1")).setScale(2, RoundingMode.HALF_EVEN))
: Maybe.nothing();
Maybe<List<LineItem>> updated = modifyAllMaybe(allPrices, raiseTenPercent, items);
// Just([LineItem[sku=SKU-1, quantity=1, price=1099.99],
// LineItem[sku=SKU-2, quantity=2, price=32.99]])
List<LineItem> withACheapItem =
List.of(items.get(0), new LineItem("SKU-3", 3, new BigDecimal("4.99")));
Maybe<List<LineItem>> refused = modifyAllMaybe(allPrices, raiseTenPercent, withACheapItem);
// Nothing: 4.99 is under 10, so no price changes
Use for atomic updates where all modifications must succeed or none should apply, for example, applying currency conversion where partial conversion would leave data inconsistent.
modifyAllEither: First Error Only
Returns Either.right(updated) if all validations pass, Either.left(firstError) if any fail. The result keeps only the first error; the traversal still visits every element. An element the traversal passes over, such as a null one that filtered or a prism leaves out, stays as it is, though a Right could not hold it. The same holds for modifyAllValidated and modifyAllMaybe.
List<LineItem> withRefunds =
List.of(
new LineItem("SKU-1", 1, new BigDecimal("999.99")),
new LineItem("SKU-4", 1, new BigDecimal("-5.00")),
new LineItem("SKU-5", 1, new BigDecimal("-1.50")));
Either<String, List<LineItem>> result =
modifyAllEither(
allPrices,
price -> {
if (price.compareTo(BigDecimal.ZERO) < 0) {
return Either.left("Price cannot be negative: " + price);
}
return Either.right(price);
},
withRefunds);
// Left(Price cannot be negative: -5.00): the first failure wins,
// though every price is checked
Use when one error is all the caller will act on, for example an API request you reject as soon as it is known to be invalid. Note this shapes the answer, not the work: every element is still validated before the Either collapses.
modifyAllValidated: Error Accumulation
Returns Validated.valid(updated) if all validations pass, Validated.invalid(allErrors) if any fail. Collects all errors.
Validated<List<String>, List<LineItem>> result = modifyAllValidated(
allPrices,
price -> {
if (price.compareTo(BigDecimal.ZERO) < 0) {
return Validated.invalid("Price cannot be negative: " + price);
}
return Validated.valid(price);
},
items
);
// Checks ALL items and collects ALL errors
// Validated exposes fold, not match
if (result.isInvalid()) {
List<String> errors = result.getError();
System.out.println("Validation failed with " + errors.size() + " errors:");
errors.forEach(err -> System.out.println(" - " + err));
} else {
System.out.println("All items valid");
}
Use for error accumulation where you want to collect all errors, for example, form validation where users need to see all problems at once rather than one at a time.
modifyWherePossible: Selective Modification
Modifies elements where the function returns Maybe.just(value), leaves others unchanged. Best-effort operation that always succeeds.
Lens<Order, OrderStatus> statusLens = OrderLenses.status();
Traversal<List<Order>, OrderStatus> allStatuses =
Traversals.<Order>forList().andThen(statusLens);
// Ship only the PAID orders
List<Order> updated = modifyWherePossible(
allStatuses,
status -> status == OrderStatus.PAID
? Maybe.just(OrderStatus.SHIPPED)
: Maybe.nothing(), // Leave NEW and SHIPPED orders unchanged
orders
);
Use for selective updates where only some elements should be modified, for example, status transitions that only affect orders in a certain state.
Analysis Methods
countValid: Count Passing Validation
Count how many elements pass validation without modifying anything.
int validCount = countValid(
allPrices,
price -> price.compareTo(BigDecimal.ZERO) >= 0
? Either.right(price)
: Either.left("Negative price"),
items
);
System.out.println("Valid items: " + validCount + " out of " + items.size());
collectErrors: Gather Validation Failures
Collect all validation errors without modifying anything. Returns empty list if all valid.
List<String> errors = collectErrors(
allPrices,
price -> price.compareTo(BigDecimal.ZERO) >= 0
? Either.right(price)
: Either.left("Negative price: " + price),
items
);
if (errors.isEmpty()) {
System.out.println("All prices valid");
} else {
System.out.println("Found " + errors.size() + " invalid prices:");
errors.forEach(err -> System.out.println(" - " + err));
}
Complete Example: Order Validation Pipeline
public sealed interface OrderVerdict permits OrderApproved, OrderRejected {}
record OrderApproved(Order order) implements OrderVerdict {}
record OrderRejected(List<String> errors) implements OrderVerdict {}
public OrderVerdict validateOrder(Order order) {
Lens<LineItem, BigDecimal> priceLens = LineItemLenses.price();
Lens<LineItem, Integer> quantityLens = LineItemLenses.quantity();
Traversal<List<LineItem>, BigDecimal> allPrices =
Traversals.<LineItem>forList().andThen(priceLens);
Traversal<List<LineItem>, Integer> allQuantities =
Traversals.<LineItem>forList().andThen(quantityLens);
// Step 1: Validate all prices (accumulate errors)
List<String> priceErrors = collectErrors(
allPrices,
price -> validatePrice(price),
order.lines()
);
// Step 2: Validate all quantities (accumulate errors)
List<String> quantityErrors = collectErrors(
allQuantities,
qty -> validateQuantity(qty),
order.lines()
);
// Step 3: Combine all errors
List<String> allErrors = Stream.of(priceErrors, quantityErrors)
.flatMap(List::stream)
.toList();
if (!allErrors.isEmpty()) {
return new OrderRejected(allErrors);
}
// Step 4: Apply discounts to valid items
List<LineItem> discounted = modifyWherePossible(
allPrices,
price -> price.compareTo(new BigDecimal("100")) > 0
? Maybe.just(price.multiply(new BigDecimal("0.9")).setScale(2, RoundingMode.HALF_EVEN))
: Maybe.nothing(),
order.lines()
);
return new OrderApproved(OrderLenses.lines().set(discounted, order));
}
private Either<String, BigDecimal> validatePrice(BigDecimal price) {
if (price.compareTo(BigDecimal.ZERO) < 0) {
return Either.left("Price cannot be negative");
}
if (price.compareTo(new BigDecimal("10000")) > 0) {
return Either.left("Price exceeds maximum");
}
return Either.right(price);
}
private Either<String, Integer> validateQuantity(Integer qty) {
if (qty <= 0) {
return Either.left("Quantity must be positive");
}
if (qty > 100) {
return Either.left("Quantity exceeds maximum");
}
return Either.right(qty);
}
Best Practices
First error only (modifyAllEither):
- API requests rejected with one reason
- Internal callers that act on the first problem
- Every element is still validated, so this does not save the work
Error accumulation (modifyAllValidated):
- Form validation (show all errors)
- Batch processing (complete error report)
- Better user experience
// Good: Pure validator
private Either<String, String> validateEmail(String email) {
if (!email.contains("@")) {
return Either.left("Invalid email");
}
return Either.right(email.toLowerCase());
}
// Avoid: Impure validator with side effects
private Either<String, String> validateEmailAndLog(String email) {
logger.info("Validating email: {}", email); // Side effect
if (!email.contains("@")) {
return Either.left("Invalid email");
}
return Either.right(email.toLowerCase());
}
Pure functions are easier to test, reason about, and compose.
Lens extensions handle null field values, but not null source objects:
Affiliate affiliate = null;
Maybe<String> bio = getMaybe(bioLens, affiliate); // NullPointerException!
// Wrap the source in Maybe first
Maybe<Affiliate> maybeAffiliate = Maybe.fromNullable(affiliate);
Maybe<String> safeBio = maybeAffiliate.flatMap(a -> getMaybe(bioLens, a));
Every extension at a glance
| Method | Returns | Use Case |
|---|---|---|
getMaybe | Maybe<A> | Null-safe field access |
getEither | Either<E, A> | Access with error message |
modifyMaybe | Maybe<S> | Optional modification |
modifyEither | Either<E, S> | Fail-fast single field validation |
modifyTry | Try<S> | Exception-safe modifications |
modifyAllMaybe | Maybe<S> | All-or-nothing bulk modification |
modifyAllEither | Either<E, S> | Bulk validation, first error only |
modifyAllValidated | Validated<List<E>, S> | Error accumulation |
modifyWherePossible | S | Selective modification |
countValid | int | Count valid elements |
collectErrors | List<E> | Gather all errors |
getValidated | Validated<E, A> | Access, accumulating the failure |
modifyValidated | Validated<E, S> | Single-field modification, accumulating |
setIfValid | Either<String, S> | Write only when the new value passes |
getAllMaybe | Maybe<List<A>> | Extract all, or nothing when empty |
- The extensions are the error-handling half of an optic. A
Lensgets you to a field;getEither,modifyEitherandmodifyTrydecide what happens when getting there, or changing it, can fail. - The suffix names the failure shape, not the operation.
Maybefor "no detail",Eitherfor "first error",Tryfor "it threw",Validatedfor "every error at once". Pick the suffix from what the caller needs to hear. modifyAll*is the bulk family. All-or-nothing, first-error and accumulating are three different answers to one traversal, and the return type states which you chose. All three visit every element: the suffix shapes the answer, not the work.modifyWherePossibleis deliberately total. It never fails; elements that cannot be modified are left as they are, which makes it the right tool for best-effort passes and the wrong one for validation.countValidandcollectErrorsinspect without writing. They answer "would this succeed, and why not" before you commit to a modification.
- Core Type Integration: the prisms and traversals for the
Maybe/Either/Validated/Trythese methods return - Updates That Can Fail: the same validation strategies as
OpticOpsstatics and builders - Deep Validation with
modifyF: the longer example these operations shorten
Previous: Core Type Integration Next: Optics for External Types