Skip to content

Conversation

@Stanislav-Zabramnyi
Copy link
Contributor

No description provided.

Copy link
Contributor

@tboychuk tboychuk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please take a look at my comments. Thanks


public RandomFieldComparator(Class<T> targetType) {
Objects.requireNonNull(targetType);
this.targetType = targetType;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes sense to do this.targetType = Objects.requireNonNull(targetType); or even
this.targetType = requireNonNull(targetType);

var field1 = (Comparable) fieldToCompare.get(o1);
var field2 = (Comparable) fieldToCompare.get(o2);

return Comparator.<Comparable>nullsLast(Comparator.naturalOrder()).compare(field1, field2);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd move comparator into a local variable to make this line cleaner.

Objects.requireNonNull(o1);
Objects.requireNonNull(o2);
fieldToCompare.setAccessible(true);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You user Comparable as raw type (without specifying a generic type), while you can actually provide a type argument and use it property. Both field values have the same type, so you need to create a helper method for compiler to catch that type.

@Override
    public int compare(T o1, T o2) {
        Objects.requireNonNull(o1);
        Objects.requireNonNull(o2);
        return compareFieldValues(o1, o2);
    }

    @SneakyThrows
    @SuppressWarnings("unchecked")
    private <U extends Comparable<? super U>> int compareFieldValues(T o1, T o2) {
        field.setAccessible(true);
        var value1 = (U) field.get(o1);
        var value2 = (U) field.get(o2);
        Comparator<U> comparator = Comparator.nullsLast(Comparator.naturalOrder());
        return comparator.compare(value1, value2);
    }

What I like about helper method is that you can put @SneakyThrows and well as @SuppressWarnings there, which makes method compare clean and simple. 🤷🏻‍♂️

@Stanislav-Zabramnyi Stanislav-Zabramnyi merged commit ee914af into completed Aug 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants