Skip to content

jabrena/plinth / skills/141-java-refactoring-with-modern-features

141-java-refactoring-with-modern-features

Verified

Use when you need to refactor Java code to adopt modern Java features (Java 8+) — including migrating anonymous classes to lambdas, replacing Iterator loops with Stream API, adopting Optional for null safety, switching from legacy Date/Calendar to java.time, using collection factory methods, applying text blocks, var inference, or leveraging Java 25 features like flexible constructor bodies and module import declarations. This should trigger for requests such as Review Java code for modern Java development; Apply best practices for modern Java development in Java code; Modernize Java code with records pattern matching or switch expressions; Replace legacy idioms with modern Java features; Adopt Java 8+ language features safely. Part of Plinth Toolkit

references/141-java-refactoring-with-modern-features.md

View on GitHub
---
name: 141-java-refactoring-with-modern-features
description: Use when you need to refactor Java code to adopt modern Java features (Java 8+) including lambda expressions, Stream API, Optional, java.time API, collection factory methods, text blocks, var inference, and Java 25 flexible constructor bodies and module import declarations.
license: Apache-2.0
metadata:
  author: Juan Antonio Breña Moral
  version: 0.19.0
---
# Modern Java Development Guidelines (Java 8+)

## Role

You are a Senior software engineer with extensive experience in Java software development

## Goal

Modern Java development (Java 8+) emphasizes leveraging lambda expressions and functional interfaces over anonymous classes, and using the Stream API for declarative collection processing. The `Optional` API should be used for handling potentially absent values gracefully, and the `java.time` API for all date/time operations. Default methods allow non-breaking interface evolution. Local Variable Type Inference (`var`) can improve readability when used judiciously. Unmodifiable collection factory methods (`List.of()`, etc.) provide concise immutable collections. The Java Platform Module System (JPMS, Java 9+) enables strong encapsulation. Java 25 introduces Flexible Constructor Bodies (JEP 513) for enhanced initialization patterns and Module Import Declarations (JEP 511) for simplified module dependencies. Performance implications of new features should be considered and profiled. Testing strategies need to adapt to these modern features, and text blocks (Java 15+) offer improved readability for multi-line strings.

### Key Principles

1. **Functional Programming**: Leverage lambda expressions, method references, and functional interfaces
2. **Type Safety**: Use Optional for null safety and appropriate generic types
3. **Clear Intent**: Choose descriptive names and use modern APIs that express intent clearly
4. **Performance Awareness**: Consider performance implications of modern features
5. **Type Design**: Apply typography-inspired principles to code structure

## Constraints

Before applying any recommendations, ensure the project is in a valid state by running Maven compilation. Compilation failure is a BLOCKING condition that prevents any further processing.

- **MANDATORY**: Run `./mvnw compile` or `mvn compile` before applying any change
- **PREREQUISITE**: Project must compile successfully and pass basic validation checks before any optimization
- **CRITICAL SAFETY**: If compilation fails, IMMEDIATELY STOP and DO NOT CONTINUE with any recommendations
- **BLOCKING CONDITION**: Compilation errors must be resolved by the user before proceeding with any object-oriented design improvements
- **NO EXCEPTIONS**: Under no circumstances should design recommendations be applied to a project that fails to compile

## Examples

### Table of contents

- Example 1: Lambda Expressions and Functional Interfaces
- Example 2: Stream API
- Example 3: Optional API
- Example 4: Date/Time API (java.time)
- Example 5: Default Methods in Interfaces
- Example 6: Local Variable Type Inference (var)
- Example 7: Collection Factory Methods
- Example 8: Module System (Java 9+) with Import Declarations (Java 25)
- Example 9: Performance Considerations with Modern Features
- Example 10: Testing Modern Java Code
- Example 11: Use Text Blocks for Readable Multi-line Strings
- Example 12: Flexible Constructor Bodies (Java 25)

### Example 1: Lambda Expressions and Functional Interfaces

Title: Effectively Use Lambda Expressions and Functional Interfaces
Description: - Prefer lambda expressions over anonymous inner classes for concise implementation of functional interfaces. - Keep lambda expressions short, readable, and focused on a single piece of logic. - Use method references (e.g., `System.out::println`, `String::isEmpty`) when they are clearer and more direct than an equivalent lambda. - Leverage the rich set of built-in functional interfaces from the `java.util.function` package (e.g., `Predicate`, `Function`, `Consumer`, `Supplier`). - Create custom functional interfaces only when a specific signature is needed that isn't covered by built-in ones. - Always annotate custom functional interfaces with `@FunctionalInterface` to ensure they meet the criteria (a single abstract method) and to clearly communicate their purpose.

**Good example:**

```java
import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;
import java.util.function.Predicate;

// Custom functional interface
@FunctionalInterface
interface DataProcessor<T, R> {
    R process(T data);
}

public class LambdaExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");

        // Good: Using method reference
        System.out.println("Printing names using method reference:");
        names.forEach(System.out::println);

        // Good: Simple lambda for filtering
        List<String> longNames = names.stream()
            .filter(str -> str.length() > 4) // Lambda expression
            .collect(Collectors.toList());
        System.out.println("\nLong names (length > 4): " + longNames);

        // Good: Using a built-in functional interface (Predicate)
        Predicate<String> startsWithA = s -> s.startsWith("A");
        List<String> namesStartingWithA = names.stream()
            .filter(startsWithA)
            .collect(Collectors.toList());
        System.out.println("Names starting with 'A': " + namesStartingWithA);

        // Good: Using a custom functional interface
        DataProcessor<String, Integer> nameLengthProcessor = name -> name.length();
        int lengthOfAlice = nameLengthProcessor.process("Alice");
        System.out.println("Length of 'Alice' using custom processor: " + lengthOfAlice);
    }
}
```

**Bad example:**

```java
import java.util.List;
import java.util.Arrays;
import java.util.function.Consumer;

public class OldStyleAnonymousClass {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob");

        // Bad: Using an anonymous inner class where a lambda would be more concise
        names.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println("Processing: " + s);
            }
        });

        // Bad: Overly complex lambda that should be a separate method
        names.stream().filter(s -> {
            System.out.println("Checking name: " + s); // Side effect in filter
            boolean isLong = s.length() > 3;
            boolean startsWithVowel = "AEIOUaeiou".indexOf(s.charAt(0)) != -1;
            return isLong && startsWithVowel; // Multiple conditions
        }).forEach(System.out::println);
    }
}
```

### Example 2: Stream API

Title: Leverage the Stream API for Collection Processing
Description: Use streams for processing sequences of elements from collections or other sources in a functional style. Prefer a declarative approach (what to do) over an imperative one (how to do it) for stream operations. Chain stream operations effectively to create a readable processing pipeline. Use appropriate terminal operations to produce a result or side-effect. Be mindful of performance implications, especially with large datasets or complex operations.

**Good example:**

```java
import java.util.List;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

public class StreamApiExample {
    public static void main(String[] args) {
        List<String> data = Arrays.asList(" apple ", null, " BANANA ", " cherry ", "apple", "  ");

        // Good: Effective stream usage for cleaning and processing data
        List<String> processedData = data.stream()
            .filter(Objects::nonNull)          // Remove nulls
            .map(String::trim)                 // Trim whitespace
            .filter(s -> !s.isEmpty())       // Remove empty strings
            .map(String::toLowerCase)          // Convert to lower case
            .distinct()                        // Keep unique elements
            .sorted()                          // Sort alphabetically
            .collect(Collectors.toList());
        System.out.println("Processed and sorted data: " + processedData);

        // Good: Complex data transformation pipeline
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        int sumOfEvenSquares = numbers.stream()
            .filter(n -> n % 2 == 0)
            .mapToInt(n -> n * n)
            .sum();
        System.out.println("Sum of squares of even numbers: " + sumOfEvenSquares);
    }
}
```

**Bad example:**

```java
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class StreamAntiPattern {
    public static void main(String[] args) {
        List<String> data = Arrays.asList("a", "b", "c");
        List<String> result = new ArrayList<>();

        // Bad: Using stream for a simple loop where a foreach loop is clearer
        // and potentially more performant for simple side effects on small lists.
        data.stream().forEach(s -> result.add(s.toUpperCase())); // Modifying external list - side effect!

        // Better (imperative but clear for this simple case, or use map().collect()):
        for (String s : data) {
            result.add(s.toUpperCase());
        }
        System.out.println("Uppercase (imperative): " + result);

        // Bad: Overusing parallel streams for simple operations on small collections
        // The overhead of parallelization can outweigh benefits.
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        int sum = numbers.parallelStream() // Unnecessary parallelization for small sum
                         .reduce(0, Integer::sum);
        System.out.println("Sum (parallel, overkill): " + sum);
    }
}
```

### Example 3: Optional API

Title: Handle Potentially Absent Values Gracefully with Optional
Description: Use `Optional<T>` to explicitly represent values that may be absent, making your API clearer about nullability. Avoid calling `Optional.get()` directly without first checking `isPresent()`. Prefer functional alternatives. Leverage `Optional`'s functional-style methods like `map()`, `flatMap()`, `filter()`, `orElse()`, `orElseGet()`, `orElseThrow()` to handle absent values in a fluent and safe manner.

**Good example:**

```java
import java.util.Optional;
import java.util.Map;

class User {
    Address address;
    String name;
    public User(String name, Address address) { this.name = name; this.address = address; }
    public Optional<Address> getAddress() { return Optional.ofNullable(address); }
    public String getName() { return name; }
}
class Address {
    Country country;
    public Address(Country c) { this.country = c; }
    public Optional<Country> getCountry() { return Optional.ofNullable(country); }
}
class Country {
    String code;
    public Country(String code) { this.code = code; }
    public String getCode() { return code; }
}

public class OptionalExample {
    private static Map<String, User> userRepository = Map.of(
        "user1", new User("Alice", new Address(new Country("US"))),
        "user2", new User("Bob", new Address(null)), // User with address, but no country
        "user3", new User("Charlie", null) // User with no address
    );

    public static String findUserCountryCode(String userId) {
        // Good: Complex Optional chain to safely navigate potentially null properties
        return Optional.ofNullable(userRepository.get(userId)) // Optional<User>
            .flatMap(User::getAddress)                         // Optional<Address>
            .flatMap(Address::getCountry)                      // Optional<Country>
            .map(Country::getCode)                             // Optional<String> (country code)
            .orElse("UNKNOWN_COUNTRY");                          // Default if any step results in empty
    }

    public static String processValue(String value) {
        // Good: Optional usage for simple processing
        return Optional.ofNullable(value)
            .map(String::trim)
            .filter(s -> !s.isEmpty())
            .map(String::toUpperCase)
            .orElse("DEFAULT_VALUE");
    }
}
```

**Bad example:**

```java
import java.util.Optional;

public class OptionalAntiPattern {

    public String getValueUnsafe(Optional<String> optValue) { // Parameter is Optional - not ideal
        // Bad: Calling .get() without isPresent() check - can throw NoSuchElementException
        if (optValue.isPresent()) { // This check is good, but often people forget it
           return optValue.get();
        }
        return "default"; // Or one might just call optValue.get() directly
    }

    public void process(String value) {
        Optional<String> optionalValue = Optional.ofNullable(value);
        // Bad: Using isPresent() and get() where orElse/map could be used
        if (optionalValue.isPresent()) {
            String s = optionalValue.get();
            System.out.println("Value is: " + s.toUpperCase());
        } else {
            System.out.println("Value is: DEFAULT");
        }
    }

    // Optional field - generally not recommended
    private Optional<String> configuration = Optional.empty();
    public void setConfiguration(String config) { this.configuration = Optional.ofNullable(config); }
}
```

### Example 4: Date/Time API (java.time)

Title: Utilize the Modern java.time API for Dates and Times
Description: Replace legacy `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` with the classes from the `java.time` package (introduced in Java 8). Choose the appropriate `java.time` class for your specific needs: `Instant` for machine time, `LocalDate` for dates without time-zone, `LocalDateTime` for date-time without time-zone, `ZonedDateTime` for date-time with specific time-zone, `Duration` for time-based amounts, and `Period` for date-based amounts.

**Good example:**

```java
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateTimeApiExample {
    public static void main(String[] args) {
        // Current date and time
        LocalDateTime now = LocalDateTime.now();
        System.out.println("Current LocalDateTime: " + now);

        // Date-specific operations
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1);
        System.out.println("Today: " + today + ", Tomorrow: " + tomorrow);
        Period period = Period.between(today, today.plusMonths(2).plusDays(5));
        System.out.println("Period of 2 months and 5 days: " + period);

        // Time-specific operations with time zones
        ZonedDateTime zonedNowUTC = ZonedDateTime.now(ZoneId.of("UTC"));
        ZonedDateTime zonedNowParis = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
        System.out.println("Current time in UTC: " + zonedNowUTC);
        System.out.println("Current time in Paris: " + zonedNowParis);

        // Machine time (timestamp)
        Instant timestamp = Instant.now();
        System.out.println("Current Instant (UTC): " + timestamp);

        // Duration between two points in time
        Instant start = Instant.now();
        try { Thread.sleep(100); } catch (InterruptedException e) { /* ignore */ }
        Instant end = Instant.now();
        Duration duration = Duration.between(start, end);
        System.out.println("Duration of operation: " + duration.toMillis() + " ms");

        // Formatting and Parsing
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        System.out.println("Formatted LocalDateTime: " + formattedNow);
        LocalDateTime parsedDateTime = LocalDateTime.parse("2023-01-15 10:30:00", formatter);
        System.out.println("Parsed LocalDateTime: " + parsedDateTime);
    }
}
```

**Bad example:**

```java
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class LegacyDateTime {
    public static void main(String[] args) {
        // Bad: Using legacy java.util.Date (mutable and confusing)
        Date oldDate = new Date();
        System.out.println("Legacy Date: " + oldDate);
        // oldDate.setMonth(5); // Deprecated and error-prone

        // Bad: Using java.util.Calendar (mutable and cumbersome API)
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        Date tomorrowOld = calendar.getTime();
        System.out.println("Legacy Calendar for tomorrow: " + tomorrowOld);

        // Bad: SimpleDateFormat is not thread-safe
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String formattedOldDate = sdf.format(oldDate);
        System.out.println("Legacy formatted date: " + formattedOldDate);
        // If sdf were shared among threads, it could lead to incorrect parsing/formatting.
    }
}
```

### Example 5: Default Methods in Interfaces

Title: Enhance Interfaces with Default Methods for Non-Breaking Evolution
Description: Use default methods to add new functionality to existing interfaces without breaking implementing classes. Keep default method implementations simple and focused. Complex logic might be better suited for helper classes or abstract base classes. Clearly document the behavior of default methods, including any assumptions they make about the interface's contract. Avoid introducing state (fields) into interfaces, as default methods cannot access instance fields directly.

**Good example:**

```java
interface DataProcessorInterface {
    String process(String data);

    // Good: Default method providing optional, additive behavior
    default String processWithLogging(String data) {
        String threadName = Thread.currentThread().getName();
        System.out.println("" + threadName + " Default Log: Starting to process data - " + data.substring(0, Math.min(10, data.length())) + "...");
        String result = process(data); // Calls the abstract method
        System.out.println("" + threadName + " Default Log: Finished processing. Result - " + result.substring(0, Math.min(10, result.length())) + "...");
        return result;
    }

    // Another default method
    default boolean isValid(String data) {
        return data != null && !data.trim().isEmpty();
    }
}

class SimpleDataProcessor implements DataProcessorInterface {
    @Override
    public String process(String data) {
        return "PROCESSED:" + data.toUpperCase();
    }
}

class AdvancedDataProcessor implements DataProcessorInterface {
    @Override
    public String process(String data) {
        return "ADVANCED_PROCESSED:" + new StringBuilder(data).reverse().toString();
    }

    // Optionally override the default method
    @Override
    public String processWithLogging(String data) {
        System.out.println("Advanced Log: Pre-processing " + data);
        String result = process(data);
        System.out.println("Advanced Log: Post-processing done.");
        return result;
    }
}
```

**Bad example:**

```java
interface BadInterface {
    void coreAction();

    // Bad: Default method with overly complex logic or many dependencies
    // that should ideally be in a separate class or abstract class.
    default String processWithComplexLogic(String input) {
        // Too much logic for a default method
        StringBuilder result = new StringBuilder();
        String[] parts = input.split(",");
        for (String part : parts) {
            if (part.trim().length() > 0) {
                result.append(part.trim().toUpperCase());
                if (!part.equals(parts[parts.length - 1])) {
                    result.append("|");
                }
            }
        }
        // Complex validation
        if (result.length() > 100) {
            throw new IllegalArgumentException("Result too long");
        }
        return result.toString();
    }
}
```

### Example 6: Local Variable Type Inference (var)

Title: Use var judiciously to improve readability
Description: Use the `var` keyword (introduced in Java 10) for local variable declarations when the type is obvious from the context and it improves readability. Avoid using `var` when it makes the code less clear or when the inferred type might not be what you expect. Use `var` with care in complex expressions or when the type provides important documentation value.

**Good example:**

```java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class VarExample {
    public void demonstrateGoodVarUsage() {
        // Good: Type is obvious from right-hand side
        var names = List.of("Alice", "Bob", "Charlie");
        var nameCount = names.size();
        var isEmpty = names.isEmpty();

        // Good: Reduces verbosity for complex generic types
        var namesByLength = names.stream()
            .collect(Collectors.groupingBy(String::length));

        // Good: Constructor call makes type obvious
        var stringBuilder = new StringBuilder();
        var file = new java.io.File("data.txt");

        // Good: Method return type is clear from method name
        var currentUser = getCurrentUser();
        var configuration = loadConfiguration();
    }

    private User getCurrentUser() { return new User(); }
    private Configuration loadConfiguration() { return new Configuration(); }
}

class User {}
class Configuration {}
```

**Bad example:**

```java
import java.util.List;

public class VarAntiPattern {
    public void demonstrateBadVarUsage() {
        // Bad: Type is not obvious, could be List<Object> or List<String>
        var data = getData();

        // Bad: Return type is ambiguous
        var result = processData(data);

        // Bad: Numeric literal type is not obvious (int? long? double?)
        var number = 42;
        var decimal = 3.14;

        // Bad: Method chain makes type unclear
        var processed = data.stream()
            .filter(item -> item != null)
            .map(item -> item.toString())
            .findFirst();

        // Bad: Using var with null (compilation error)
        // var nullValue = null; // This won't compile

        // Bad: Diamond operator with var is redundant
        // var list = new ArrayList<>(); // Type can't be inferred properly
    }

    private List<?> getData() { return List.of(); }
    private Object processData(List<?> data) { return new Object(); }
}
```

### Example 7: Collection Factory Methods

Title: Utilize Unmodifiable Collection Factory Methods
Description: Use the static factory methods `List.of()`, `Set.of()`, and `Map.of()` (Java 9+) to create compact, unmodifiable (immutable) collections when the elements are known at compile time. For creating mutable collections, continue to use traditional constructors (e.g., `new ArrayList<>()`) or Stream API collectors. Be aware that these factory methods create unmodifiable collections, do not permit `null` elements, and `Map.of()` does not permit duplicate keys.

**Good example:**

```java
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.ArrayList; // For mutable list comparison

public class CollectionFactoryExample {
    public static void main(String[] args) {
        // Good: Creating unmodifiable (immutable) collections
        List<String> unmodifiableList = List.of("alpha", "beta", "gamma");
        System.out.println("Unmodifiable List: " + unmodifiableList);
        try {
            unmodifiableList.add("delta"); // Throws UnsupportedOperationException
        } catch (UnsupportedOperationException e) {
            System.out.println("Error adding to unmodifiableList: " + e.getMessage());
        }

        Set<Integer> unmodifiableSet = Set.of(10, 20, 30, 20); // Duplicate 20 is ignored for Set
        System.out.println("Unmodifiable Set: " + unmodifiableSet);

        Map<String, Integer> unmodifiableMap = Map.of(
            "one", 1,
            "two", 2,
            "three", 3
        );
        System.out.println("Unmodifiable Map: " + unmodifiableMap);

        // Good: Creating mutable collections using traditional methods or collectors
        List<String> mutableListFromStream = Stream.of("x", "y", "z")
            .filter(s -> s.length() == 1)
            .collect(Collectors.toList()); // Creates a mutable ArrayList by default
        mutableListFromStream.add("a");
        System.out.println("Mutable list from stream: " + mutableListFromStream);

        List<String> anotherMutableList = new ArrayList<>(List.of("initial")); // Initialize mutable from unmodifiable
        anotherMutableList.add("added");
        System.out.println("Mutable list initialized from List.of: " + anotherMutableList);
    }
}
```

**Bad example:**

```java
import java.util.List;
import java.util.Set;
import java.util.Map;

public class CollectionFactoryAntiPattern {
    public static void main(String[] args) {
        // Bad: Attempting to use List.of() when null elements are needed (will throw NullPointerException)
        try {
            List<String> listWithNull = List.of("apple", null, "banana");
            System.out.println(listWithNull);
        } catch (NullPointerException e) {
            System.err.println("Error: List.of() does not accept null elements. " + e.getMessage());
        }

        // Bad: Attempting to use Map.of() with duplicate keys (will throw IllegalArgumentException)
        try {
            Map<String, Integer> mapWithDuplicateKeys = Map.of("a", 1, "b", 2, "a", 3);
            System.out.println(mapWithDuplicateKeys);
        } catch (IllegalArgumentException e) {
            System.err.println("Error: Map.of() does not accept duplicate keys. " + e.getMessage());
        }

        // Misunderstanding: Thinking List.of() returns a general-purpose mutable list
        List<String> myList = List.of("one", "two");
        // myList.add("three"); // This would throw UnsupportedOperationException at runtime
        // If mutability is needed, ArrayList should be used:
        // List<String> mutableMyList = new ArrayList<>(List.of("one", "two"));
        // mutableMyList.add("three");
    }
}
```

### Example 8: Module System (Java 9+) with Import Declarations (Java 25)

Title: Leverage the Java Platform Module System (JPMS) for Strong Encapsulation
Description: For applications built on Java 9 or later, consider designing them as modules to achieve strong encapsulation and reliable configuration. Create a `module-info.java` file at the root of your source code to declare your module. Use `requires` clauses to specify dependencies, `exports` clauses to make packages publicly available, `opens` clauses for reflection access, and `provides ... with ...` for service discovery. Java 25 introduces Module Import Declarations (JEP 511) that allow importing entire modules into the current module's namespace, simplifying access to frequently used types from other modules. Carefully consider which packages to export to maintain good encapsulation.

**Good example:**

```java
// In src/com.example.application/module-info.java
/*
module com.example.application {
    // Depends on the standard java.base and java.logging modules
    requires java.base; // Usually implicit but good to be explicit
    requires java.logging;

    // Java 25 - JEP 511: Module Import Declarations
    // Import entire modules to simplify type access
    import module java.util.concurrent;
    import module java.time;

    // Depends on an external library module (assuming it's modularized)
    requires org.example.somelibrary;
    import module org.example.somelibrary;

    // Exports its API package for other modules to use
    exports com.example.application.api;

    // If it uses a service defined in another module
    // uses com.example.spi.SomeService;

    // If it provides an implementation of a service
    // provides com.example.spi.AnotherService with com.example.application.internal.AnotherServiceImpl;
}
*/

// In src/com.example.library/module-info.java (A hypothetical library)
/*
module com.example.library {
    requires java.base;
    exports com.example.library.utils;
}
*/

// Example Java class within com.example.application.api
// package com.example.application.api;
// public class AppService { public String getGreeting() { return "Hello from AppService"; } }

public class ModuleSystemExample {
    public static void main(String[] args) {
        System.out.println("This example primarily shows conceptual module-info.java files.");
        System.out.println("To run a modular application, compile with module path and run with --module-path and --module.");
        // AppService app = new AppService();
        // System.out.println(app.getGreeting());
    }
}
```

**Bad example:**

```java
// In module-info.java
/*
module com.example.badmodule {
    // Bad: Exporting too many internal packages, breaking encapsulation
    exports com.example.badmodule.internal.utils;
    exports com.example.badmodule.internal.anotherpackage;
    exports com.example.badmodule.api; // This one might be okay

    // Bad: Requiring transitive on everything by default, can lead to a less stable module graph
    // requires transitive java.sql;
    // requires transitive com.another.library;
    // (Use 'requires transitive' only when your module's API exposes types from the transitive module)
}
*/
public class BadModuleExample {
    public static void main(String[] args) {
        System.out.println("Illustrates bad practices in module-info.java like over-exporting internals.");
    }
}
```

### Example 9: Performance Considerations with Modern Features

Title: Be Mindful of Performance Implications of Modern Java Features
Description: Always profile your application before attempting optimizations. Avoid premature optimization. Choose appropriate data structures for the task. Streams can sometimes have overhead compared to simple loops for very small collections. Parallel streams can improve performance for CPU-bound tasks on large datasets but can degrade performance if misused. `Optional` can add object allocation overhead. Lazy initialization should be implemented correctly using double-checked locking or suppliers.

**Good example:**

```java
import java.util.List;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.Objects;

// Simulate an expensive object to initialize
class ExpensiveObject {
    public ExpensiveObject() {
        System.out.println("ExpensiveObject created!");
        try { Thread.sleep(100); } catch (InterruptedException e) {} // Simulate costly creation
    }
    public void use() { System.out.println("ExpensiveObject used."); }
}

public class PerformanceConsiderations {
    // Good: Lazy initialization using double-checked locking for a singleton-like expensive resource
    private volatile ExpensiveObject instance;

    public ExpensiveObject getLazyInitializedInstance() {
        ExpensiveObject result = instance; // Read volatile field once
        if (Objects.isNull(result)) {
            synchronized (this) { // Synchronize only if instance is null
                result = instance; // Double-check
                if (Objects.isNull(result)) {
                    instance = result = new ExpensiveObject();
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        PerformanceConsiderations pc = new PerformanceConsiderations();
        System.out.println("Getting instance first time:");
        ExpensiveObject obj1 = pc.getLazyInitializedInstance();
        obj1.use();

        System.out.println("\nGetting instance second time (should be cached):");
        ExpensiveObject obj2 = pc.getLazyInitializedInstance();
        obj2.use();
        System.out.println("obj1 == obj2: " + (obj1 == obj2));

        // Regarding streams: For very large collections and CPU-bound tasks, parallel streams can help.
        // But always measure. Example:
        final int LIST_SIZE = 1_000_000;
        List<Integer> numbers = new ArrayList<>(LIST_SIZE);
        for(int i=0; i<LIST_SIZE; i++) numbers.add(i);

        long startTime = System.nanoTime();
        long sumSequential = numbers.stream().mapToLong(i -> (long)i*i).sum(); // Squaring, CPU intensive
        long endTime = System.nanoTime();
        System.out.println("\nSequential sum of squares: " + sumSequential + " in " + (endTime-startTime)/1_000_000 + "ms");

        startTime = System.nanoTime();
        long sumParallel = numbers.parallelStream().mapToLong(i -> (long)i*i).sum();
        endTime = System.nanoTime();
        System.out.println("Parallel sum of squares:   " + sumParallel + " in " + (endTime-startTime)/1_000_000 + "ms");
        // On multi-core machines, parallel *may* be faster here.
    }
}
```

**Bad example:**

```java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class PerformanceAntiPattern {
    private ExpensiveObject costlyObject; // Eagerly initialized, even if not used

    public PerformanceAntiPattern() {
        // Bad: Eagerly initializing a very expensive object that might not be needed.
        // this.costlyObject = new ExpensiveObject();
        // System.out.println("Costly object created in constructor regardless of use.");
    }

    public void sometimesUseCostlyObject() {
        // If costlyObject was initialized eagerly, its cost is paid even if this method isn't called often.
        // if (costlyObject != null && Math.random() > 0.8) costlyObject.use();
        System.out.println("Costly object would have been initialized in constructor if uncommented.");
    }

    public static void main(String[] args) {
        PerformanceAntiPattern pap = new PerformanceAntiPattern();
        pap.sometimesUseCostlyObject();

        List<Integer> smallList = List.of(1, 2, 3, 4, 5);
        // Bad: Using parallel stream for a tiny list and simple operation.
        // Overhead of parallelization likely exceeds any benefit.
        System.out.println("\nCalculating sum of small list (parallel, likely inefficient):");
        long sum = smallList.parallelStream().mapToInt(Integer::intValue).sum();
        System.out.println("Sum: " + sum);
    }
}
```

### Example 10: Testing Modern Java Code

Title: Adapt Testing Strategies for Modern Java Features
Description: Adapt testing strategies to properly test modern Java features. Focus on testing behavior rather than implementation when testing lambda expressions and functional code. Use appropriate mocking strategies for functional interfaces and streams. Ensure proper testing coverage of Optional usage patterns and edge cases. Utilize modern testing frameworks and assertion libraries that integrate well with modern Java features.

**Good example:**

```java
                import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
// For actual tests, use JUnit, TestNG, AssertJ etc.
// import org.junit.jupiter.api.Test;
// import static org.assertj.core.api.Assertions.assertThat;
// import static org.assertj.core.api.Assertions.assertThatThrownBy;

class ModernFeaturesService {
    public List<String> filterAndToUpper(List<String> input, String startsWith) {
        if (Objects.isNull(input)) return List.of();
        return input.stream()
            .filter(s -> s != null && s.startsWith(startsWith))
            .map(String::toUpperCase)
            .collect(Collectors.toList());
    }

    public Optional<String> findFirstLongString(List<String> input, int minLength) {
        if (Objects.isNull(input)) return Optional.empty();
        return input.stream()
            .filter(s -> s != null && s.length() >= minLength)
            .findFirst();
    }
}

// Conceptual Tests (using System.out for assertions for simplicity here)
public class TestingModernCodeExample {

    // @Test // Example with AssertJ style (if library was present)
    void testFilterAndToUpper_withAssertJ() {
        ModernFeaturesService service = new ModernFeaturesService();
        List<String> input = List.of("apple", "apricot", "banana", "avocado");
        List<String> result = service.filterAndToUpper(input, "ap");
        // assertThat(result).containsExactlyInAnyOrder("APPLE", "APRICOT");
        System.out.println("testFilterAndToUpper: " + result); // Expected: APPLE, APRICOT
    }

    // @Test
    void testFindFirstLongString_found_withAssertJ() {
        ModernFeaturesService service = new ModernFeaturesService();
        List<String> input = List.of("short", "verylongstring", "medium");
        Optional<String> result = service.findFirstLongString(input, 10);
        // assertThat(result).isPresent().hasValue("verylongstring");
        System.out.println("testFindFirstLongString (found): " + result); // Expected: Optionalverylongstring
    }

    // @Test
    void testFindFirstLongString_notFound_withAssertJ() {
        ModernFeaturesService service = new ModernFeaturesService();
        List<String> input = List.of("short", "medium");
        Optional<String> result = service.findFirstLongString(input, 10);
        // assertThat(result).isEmpty();
        System.out.println("testFindFirstLongString (not found): " + result); // Expected: Optional.empty
    }

    public static void main(String[] args) {
        System.out.println("These are conceptual tests. Use a testing framework for real scenarios.");
        TestingModernCodeExample tests = new TestingModernCodeExample();
        tests.testFilterAndToUpper_withAssertJ();
        tests.testFindFirstLongString_found_withAssertJ();
        tests.testFindFirstLongString_notFound_withAssertJ();
    }
}
```

**Bad example:**

```java
import java.util.List;
import java.util.Optional;

// Bad: Not testing edge cases or different lambda behaviors
public class InsufficientTesting {

    public Optional<String> processList(List<String> data) {
        // Complex logic that should be thoroughly tested
        return data.stream()
                   .filter(s -> s.length() > 5)
                   .map(s -> s.substring(0, 5))
                   .findFirst();
    }

    public static void main(String[] args) {
        InsufficientTesting it = new InsufficientTesting();
        // Only testing the "happy path"
        Optional<String> result = it.processList(List.of("longstring", "another"));
        System.out.println("Result (happy path only): " + result.orElse("NOTHING"));

        // Not tested:
        // - Empty list input
        // - List with no strings matching filter
        // - List with nulls (if stream pipeline doesn't handle them)
        // - Performance with very large lists
        // This lack of thorough testing can lead to bugs in production.
    }
}
```

### Example 11: Use Text Blocks for Readable Multi-line Strings

Title: Employ Text Blocks for Clear and Maintainable Multi-line String Literals
Description: Utilize text blocks (`"""..."""`) to represent multi-line string literals in a way that preserves indentation and formatting, making them easier to read and write, especially for embedded code snippets like JSON, XML, SQL, or HTML. Text blocks automatically handle newline characters and manage indentation. Incidental leading white space is automatically stripped from each line. You can control trailing white space and use escape sequences as needed.

**Good example:**

```java
public class TextBlockExample {
    public static void main(String[] args) {
        // Good: HTML snippet using a text block
        String html = """
            <html>
                <body>
                    <p>Hello, Java Text Blocks!</p>
                </body>
            </html>
            """;
        System.out.println("HTML:\n" + html);

        // Good: JSON snippet with preserved indentation
        String json = """
            {
                "name": "Java Text Block",
                "feature": "Multi-line strings",
                "since": 15
            }
            """;
        System.out.println("JSON:\n" + json);

        // Good: SQL query
        String query = """
            SELECT id, name, email
            FROM users
            WHERE department = 'Engineering'
            ORDER BY name;
            """;
        System.out.println("SQL Query:\n" + query);

        // Good: Controlling indentation - the content's indentation relative
        // to the closing """ is preserved.
        String indented = """
                Line 1
                  Line 2 (more indented)
            Line 3 (less indented than line 2, but aligned with Line 1 relative to closing quotes)
            """;
        System.out.println("Indented Example:\n" + indented);
    }
}
```

**Bad example:**

```java
public class OldMultiLineStringExample {
    public static void main(String[] args) {
        // Bad: Using traditional string concatenation for multi-line text
        String htmlOld = "<html>\n" +
                         "    <body>\n" +
                         "        <p>Hello, old Java strings!</p>\n" +
                         "    </body>\n" +
                         "</html>\n";
        System.out.println("Old HTML:\n" + htmlOld);

        // Bad: Hard to read and maintain SQL query
        String queryOld = "SELECT id, name, email\n" +
                          "FROM users\n" +
                          "WHERE department = 'Engineering'\n" +
                          "ORDER BY name;\n";
        System.out.println("Old SQL Query:\n" + queryOld);

        // Bad: Incorrectly trying to manage indentation within a text block
        // by having significant content on the same line as opening """
        // (This can work, but it's less clear than starting content on new line)
        String mixedStyle = """   This is the first line.
                                     This is the second line.
                             """; // The indentation is determined by the least indented line or the closing """
        System.out.println("Mixed Style (potentially confusing indentation):\n" + mixedStyle);
    }
}
```

### Example 12: Flexible Constructor Bodies (Java 25)

Title: Leverage Enhanced Constructor Initialization Patterns
Description: Java 25 introduces Flexible Constructor Bodies (JEP 513) that allow statements to appear before explicit constructor invocations (super() or this() calls). This enables validation, preprocessing, and initialization logic to be executed before calling the parent constructor or another constructor in the same class. This feature enhances constructor flexibility while maintaining type safety and initialization guarantees.

**Good example:**

```java
// GOOD: Using flexible constructor bodies for validation and preprocessing
import java.util.Objects;
import java.util.List;
import java.util.ArrayList;

public class FlexibleConstructorExample {

    static class ValidatedUser {
        private final String name;
        private final String email;
        private final int age;

        public ValidatedUser(String name, String email, int age) {
            // Java 25 - JEP 513: Statements before super() call
            Objects.requireNonNull(name, "Name cannot be null");
            Objects.requireNonNull(email, "Email cannot be null");

            if (name.trim().isEmpty()) {
                throw new IllegalArgumentException("Name cannot be empty");
            }

            if (!email.contains("@")) {
                throw new IllegalArgumentException("Invalid email format");
            }

            if (age < 0 || age > 150) {
                throw new IllegalArgumentException("Age must be between 0 and 150");
            }

            // Now call super() after validation
            super();

            this.name = name.trim();
            this.email = email.toLowerCase();
            this.age = age;
        }
    }

    static class ProcessedData {
        private final List<String> items;
        private final String summary;

        public ProcessedData(List<String> rawItems) {
            // Preprocessing before this() call
            if (rawItems == null) {
                rawItems = new ArrayList<>();
            }

            List<String> cleanedItems = rawItems.stream()
                .filter(Objects::nonNull)
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .toList();

            String processedSummary = "Processed " + cleanedItems.size() + " items";

            // Call another constructor with processed data
            this(cleanedItems, processedSummary);
        }

        public ProcessedData(List<String> items, String summary) {
            super();
            this.items = new ArrayList<>(items);
            this.summary = summary;
        }

        public List<String> getItems() { return new ArrayList<>(items); }
        public String getSummary() { return summary; }
    }

    public static void main(String[] args) {
        try {
            ValidatedUser user = new ValidatedUser("John Doe", "john@example.com", 30);
            System.out.println("Created user: " + user.name);

            ProcessedData data = new ProcessedData(List.of("  item1  ", null, "", "item2", "  item3  "));
            System.out.println("Summary: " + data.getSummary());
            System.out.println("Items: " + data.getItems());

        } catch (IllegalArgumentException e) {
            System.err.println("Validation error: " + e.getMessage());
        }
    }
}
```

**Bad example:**

```java
// AVOID: Traditional constructor limitations requiring workarounds
public class TraditionalConstructorExample {

    static class User {
        private final String name;
        private final String email;
        private final int age;

        public User(String name, String email, int age) {
            // BAD: Cannot perform validation before super() call in traditional Java
            super(); // Must be first statement

            // Validation happens after super() call, which is less ideal
            if (name == null || name.trim().isEmpty()) {
                throw new IllegalArgumentException("Invalid name");
            }

            if (email == null || !email.contains("@")) {
                throw new IllegalArgumentException("Invalid email");
            }

            if (age < 0 || age > 150) {
                throw new IllegalArgumentException("Invalid age");
            }

            this.name = name.trim();
            this.email = email.toLowerCase();
            this.age = age;
        }
    }

    static class ProcessedData {
        private final List<String> items;
        private final String summary;

        public ProcessedData(List<String> rawItems) {
            // BAD: Cannot preprocess data before this() call
            // Need to use static factory method or separate validation
            this(validateAndClean(rawItems), createSummary(rawItems));
        }

        public ProcessedData(List<String> items, String summary) {
            super();
            this.items = items;
            this.summary = summary;
        }

        // BAD: Need separate static methods for preprocessing
        private static List<String> validateAndClean(List<String> rawItems) {
            if (rawItems == null) return new ArrayList<>();
            return rawItems.stream()
                .filter(Objects::nonNull)
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .toList();
        }

        private static String createSummary(List<String> rawItems) {
            int count = rawItems == null ? 0 : (int) rawItems.stream()
                .filter(Objects::nonNull)
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .count();
            return "Processed " + count + " items";
        }
    }
}
```


## Output Format

- **ANALYZE** Java code to identify specific modern feature refactoring opportunities and categorize them by impact (CRITICAL, MAINTAINABILITY, PERFORMANCE, READABILITY) and area (lambda expressions, stream API, Optional usage, java.time API, collection factories, text blocks, pattern matching, flexible constructor bodies, module import declarations)
- **CATEGORIZE** modern Java refactoring improvements found: Legacy Code Issues (anonymous classes vs lambda expressions, Iterator loops vs Stream API, null checks vs Optional usage, Date/Calendar vs java.time API), Performance Opportunities (sequential loops vs parallel streams, traditional collections vs factory methods), Readability Enhancements (verbose lambdas vs method references, string concatenation vs text blocks, explicit types vs var inference), Modern API Adoption (traditional switch vs pattern matching, verbose collection creation vs factory methods), and Java 25 Features (traditional constructor limitations vs flexible constructor bodies, verbose module dependencies vs module import declarations)
- **APPLY** modern Java features directly by implementing the most appropriate improvements for each identified opportunity: Convert anonymous classes to lambda expressions and method references, replace Iterator loops with Stream API operations, introduce Optional for null-safe method returns, migrate Date/Calendar to java.time API, adopt collection factory methods for immutable collections, replace string concatenation with text blocks for multi-line strings, integrate pattern matching for cleaner conditional logic, apply flexible constructor bodies for enhanced initialization (Java 25), and utilize module import declarations for simplified module dependencies (Java 25)
- **IMPLEMENT** comprehensive modern Java refactoring using proven patterns: Establish lambda expressions with method references for functional interfaces, integrate Stream API with proper collectors and operations (map, filter, reduce), adopt Optional throughout the codebase for null-safe operations, migrate to java.time API with LocalDate, LocalDateTime, and ZonedDateTime, utilize text blocks for improved string readability, apply var type inference where it enhances readability, integrate pattern matching for switch expressions and instanceof checks, leverage flexible constructor bodies for validation and preprocessing (Java 25), and implement module import declarations for cleaner module organization (Java 25)
- **REFACTOR** code systematically following the modern Java improvement roadmap: First convert anonymous classes to lambda expressions and method references for immediate readability gains, then replace Iterator loops with Stream API operations for functional programming benefits, introduce Optional for null-safe method signatures and operations, migrate Date/Calendar usage to modern java.time API, adopt collection factory methods and modern collection patterns, apply text blocks and var inference for code clarity, implement pattern matching where supported for cleaner conditional logic, upgrade constructor patterns with flexible constructor bodies (Java 25), and simplify module dependencies with import declarations (Java 25)
- **EXPLAIN** the applied modern Java improvements and their benefits: Code readability enhancements through lambda expressions and method references, maintainability improvements via Stream API and functional programming patterns, null-safety gains from Optional adoption, date/time handling improvements through java.time API, performance benefits from parallel streams, constructor flexibility gains from flexible constructor bodies (Java 25), module organization improvements through import declarations (Java 25), and overall code modernization through contemporary Java idioms and patterns
- **VALIDATE** that all applied modern Java refactoring compiles successfully, maintains existing functionality, preserves business logic integrity, achieves expected performance characteristics, and follows modern Java best practices through comprehensive testing and verification


## Safeguards

- **BLOCKING SAFETY CHECK**: ALWAYS run `./mvnw compile` or `mvn compile` before ANY modern Java refactoring recommendations - compilation failure is a HARD STOP
- **CRITICAL VALIDATION**: Execute `./mvnw clean verify` or `mvn clean verify` to ensure all tests pass after applying modern Java features
- **MANDATORY VERIFICATION**: Confirm all existing functionality remains intact after modern Java refactoring, especially behavioral equivalence of lambda conversions
- **SAFETY PROTOCOL**: If ANY compilation error occurs during modernization, IMMEDIATELY cease recommendations and require user intervention
- **PERFORMANCE VALIDATION**: Ensure modern Java features don't introduce performance regressions, especially with stream operations and Optional usage patterns
- **ROLLBACK REQUIREMENT**: Ensure all modern Java refactoring changes can be easily reverted if they introduce issues or performance problems
- **INCREMENTAL SAFETY**: Apply modern Java features incrementally, validating compilation and tests after each significant refactoring step
- **DEPENDENCY VALIDATION**: Check that modern Java features are compatible with project's target Java version and don't break existing dependencies
- **FINAL VERIFICATION**: After completing all modern Java improvements, perform a final full project compilation, test run, and basic performance check
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 321kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 321kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 321kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 321kUpdated Claude CodeCodexVerifiedInstall