Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A codebase uses Java 8 features heavily but in a dated style: anonymous classes, Optional.get() everywhere, and streams with side effects. You are reviewing it before a Java 21 upgrade. What do you prioritise changing and why?

I would fix correctness first: streams that mutate shared state, which break under parallel execution and hide bugs, and Optional.get() calls without a check, which are null pointer exceptions with another name. Readability changes, such as turning simple anonymous classes into lambdas, come second and are made when the code is touched, not in a big rewrite. The upgrade is a good moment to adopt clear wins such as records for DTOs and switch expressions where code changes anyway, and mechanical changes are best left to OpenRewrite with a human review.

Why this question is asked

Every long-lived codebase carries the style of the year it was written. Before a major upgrade, it is tempting either to change nothing or to modernise everything, and both are costly mistakes. Interviewers ask this scenario to see how we prioritise: what is a real defect, what is taste, and what is worth doing now. In this answer, we will look at the correctness problems first with examples, then readability, then decide what to adopt from newer Java during the upgrade, and finally how to let tools do the mechanical work.

1Correctness First: Streams With Side Effects

A stream pipeline is meant to describe a computation, not to change things outside itself. Code that adds to a shared list from inside forEach or map works by accident in a sequential stream, and breaks as soon as someone adds parallel() or reuses the code in a concurrent context.

Java
// Dated: mutating shared state from inside the stream
List<String> emails = new ArrayList<>();
users.parallelStream().filter(User::active).forEach(u -> emails.add(u.email()));
System.out.println(emails.size()); // sometimes 9998 instead of 10000, or an exception
// Fixed: let the stream build the result
List<String> emails = users.parallelStream()
.filter(User::active)
.map(User::email)
.toList(); // Java 16+; collect(Collectors.toList()) on 8
System.out.println(emails.size()); // 10000

Notice that the broken version loses elements because ArrayList is not thread safe, and the bug only shows up under load. The fixed version has no shared state at all. The same applies to counters incremented inside map and to lookups that modify a cache from inside a lambda. These are bugs, so they go to the top of the list even if the code is otherwise untouched.

2Correctness First: Optional.get() Without a Check

Optional exists to make the empty case visible. Calling get() without checking throws NoSuchElementException when the value is absent, which is exactly the failure Optional was meant to prevent.

Java
// Dated
String name = repo.findById(id).get().getName(); // NoSuchElementException if not found
// Fixed, choosing the behaviour explicitly
String name = repo.findById(id)
.map(User::getName)
.orElseThrow(() -> new UserNotFound(id)); // clear error with the id
String label = repo.findById(id).map(User::getName).orElse("unknown");

Notice that the fix forces a decision: is a missing user an error or a default? Java 10 added orElseThrow() without arguments as a clearer name for get(), but the real improvement is choosing the right behaviour. A search for .get() on Optional values across the codebase, which static analysis tools can do, finds these quickly.

3Readability Second: Anonymous Classes and Style

Anonymous classes such as new Comparator<User>() { public int compare(...) {...} } work correctly; they are just noisy. Turning simple ones into lambdas or Comparator.comparing(User::age) makes code shorter and clearer. But rewriting working code across hundreds of files only for style creates risk and review load for little gain, and it buries the real changes of the upgrade in noise.

So the rule is: change style when the code is touched for another reason, following the boy scout rule of leaving it a little better. One exception is an anonymous class created inside an instance method and stored for a long time, such as a listener or a cached callback: it keeps a reference to its enclosing object and can keep large objects alive, while a lambda only captures this when it uses it. A memory leak like that is a correctness issue and moves up.

How to prioritise the review
FindingKindWhen to change
Streams mutating shared stateBug, concurrencyNow, with tests
Optional.get() without a checkBug, hidden failureNow
Simple anonymous classesReadabilityWhen the file is touched
DTO classes with boilerplateModernisationWhen changed, as records
Long if-else on enumsModernisationWhen changed, as switch expressions

4Using the Upgrade for Clear Wins

Java 21 gives features that are worth adopting where code changes anyway. Records replace data classes with constructor, getters, equals, hashCode and toString in one line, which is ideal for DTOs and value objects; they are not suitable for JPA entities, which need a no-argument constructor and mutable fields. Switch expressions remove fall-through bugs and return a value. Pattern matching for instanceof removes casts. Text blocks make SQL and JSON in tests readable.

Java
// Before: a 40-line DTO with getters, equals, hashCode and toString
// After
public record OrderSummary(String id, BigDecimal total, Instant placedAt) {}
String level = switch (status) { // no fall-through, compiler checks enums
case NEW, PENDING -> "open";
case SHIPPED -> "in transit";
case DELIVERED, CANCELLED -> "closed";
};

Notice that both changes reduce the chance of bugs as well as length: a record's equals cannot forget a field, and a switch expression over an enum must cover every constant. We still adopt them gradually, with a team agreement on where they apply.

5Let Tools Do the Mechanical Work

Many of these changes are mechanical and can be automated. OpenRewrite has recipes that migrate a codebase to Java 21, replace anonymous classes with lambdas, add pattern matching and update deprecated APIs, and it runs as a Maven or Gradle plugin. Static analysis such as Error Prone, SonarQube or IntelliJ inspections finds Optional misuse and side effects in streams. We run the tools in small batches, one recipe per pull request, so reviewers can check the diff and tests prove nothing changed in behaviour.

6Follow-up questions

Should we turn every stream with forEach into a for loop?

No. forEach with a side effect at the very end, such as logging or sending each item, is fine. The problem is mutating shared state from inside intermediate operations or collecting results by hand. When the logic is complex, a plain for loop is often clearer than a long stream, and that is acceptable.

Are there Java 8 APIs we must replace for Java 21?

Some internal APIs such as sun.misc.BASE64Encoder are gone, Nashorn was removed in 15, and libraries using deep reflection need upgrades because strong encapsulation is enforced since 17. Those must be fixed for the upgrade itself; style changes are optional.

How do you stop the old style coming back?

Agree on the conventions, enable the matching inspections in the build, and include examples in the team's guidelines. Reviews then focus on design rather than style.

7Conclusion

In this answer, we prioritised the review by impact. Streams that mutate shared state and unchecked Optional.get() calls are real bugs, so we fix them first with tests. Anonymous classes and other style issues are changed when the code is touched, not in a big rewrite. The Java 21 upgrade is a chance to adopt records and switch expressions where code changes anyway, and OpenRewrite and static analysis handle the mechanical work in small, reviewed batches.

What to say in the interviewAbout 80 seconds aloud

Open with

I would separate defects from style. Two of these patterns are actual bugs. Streams with side effects, like adding to a shared ArrayList from forEach or map, only work while the stream is sequential; with parallel() or concurrent reuse they lose elements or throw, and they hide intent.

Then, if they want more

I would rewrite them to let the stream build the result with map and toList. And Optional.get() without a check is a NoSuchElementException waiting for a missing row, so I would replace it with orElseThrow with a meaningful exception, or orElse, depending on what should happen. Those I fix first, with tests, regardless of whether the code is being touched.

Anonymous classes are only noisy, so turning simple ones into lambdas is a readability improvement that I do when a file is changed anyway, because a mass rewrite adds risk and buries the real upgrade changes.

The upgrade itself is a good moment to adopt clear wins where code changes: records for DTOs, though not for JPA entities, switch expressions, pattern matching for instanceof and text blocks.

And for anything mechanical, I would use OpenRewrite recipes, one recipe per pull request so the diff is reviewable, plus static analysis to catch Optional misuse and keep the old style from coming back.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, Java 10, Java 16
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A codebase uses Java 8 features heavily but in a dated style: anonymous classes...": https://scrivio-interview-library.netlify.app/java/java-versions/c07d8eb4ef/