1

I have the following code in Java and I want to minimize it or write it in a more concise way. Can you help me if this is feasible?

return( Objects.equals(obj1.getMeaning(), obj2.getMeaning())
        && Objects.equals(obj1.getModifies(), obj2.getModifies())
        && Objects.equals(obj1.getOriginalCommentString(), obj2.getOriginalCommentString())
        && Objects.equals(obj1.getReferences(), obj2.getReferences())
        && Objects.equals(obj1.getReturnDescription(), obj2.getReturnDescription())
        && Objects.equals(obj1.getReturnType(), obj2.getReturnType())
        && Objects.equals(obj1.getSuppressions(), obj2.getSuppressions())
        && Objects.equals(obj1.getTemplateTypeNames(), obj2.getTemplateTypeNames())
        && Objects.equals(obj1.getThisType(), obj2.getThisType())
        && Objects.equals(obj1.getThrownTypes(), obj2.getThrownTypes())
        && Objects.equals(obj1.getTypedefType(), obj2.getTypedefType())
        && Objects.equals(obj1.getType(), obj2.getType())
        && Objects.equals(obj1.getVersion(), obj2.getVersion())
        && Objects.equals(obj1.getVisibility(), obj2.getVisibility()))

Is it a good practice to give a list of the methods, as strings, and then create a map function to test them all one by one. I have read about reflection in Java but I am not that proficient.

konsalex
  • 425
  • 5
  • 15

1 Answers1

4

You could have a method like:

<T> boolean equals(T obj1, T obj2, Iterable<? extends Function<? super T, ?>> fns) {
  for (Function<? super T, ?> fn : fns) {
    if (!Objects.equals(fn.apply(obj1), fn.apply(obj2))) {
      return false;
    }
  }
  return true;
}

and then call it like:

return equals(obj1, obj2, Arrays.asList(Thing::getMeaning, Thing::getModifies));

etc.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243