Skip to content

Generics with PECS principle #215

@agoss94

Description

@agoss94

Hi, I think some methods in DiffUtils should be adjusted to allow more flexibility with the involved List. The current implementation has the following method signature:

public static <T> Patch<T> diff(List<T> source, List<T> target, BiPredicate<T, T> equalizer)
This is a hindrance as it stipulates that both source and target lists must be of the exact same type. In practice, this is unnecessarily restrictive. Consider this more flexible alternative:

public static <T> Patch<T> diff(List<? extends T> source, List<? extends T> target, BiPredicate<? super T, ? super T> equalizer)
This version supports more general use cases while preserving type safety. For example, using Number as the common supertype:

List<Integer> source = List.of(1, 2, 3);
List<Double> target = List.of(1.0, 2.0, 4.0);

Patch<Number> patch = DiffUtils.diff(
    source,
    target,
    (a, b) -> a.doubleValue() == b.doubleValue()
);

Here, both Integer and Double extend Number, and the equality check uses doubleValue() for comparison. This is a clean and expressive use case where the current method signature would force an awkward workaround like converting one list's elements to the other type, which is unnecessary and inefficient.

Adjusting the method signature as suggested increases reusability, expressiveness, and compatibility with common JDK patterns involving inheritance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions