-
-
Notifications
You must be signed in to change notification settings - Fork 464
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Gp 155/random field comparator/completed #137
Gp 155/random field comparator/completed #137
Conversation
There was a problem hiding this 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; |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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); | ||
|
There was a problem hiding this comment.
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. 🤷🏻♂️
No description provided.