|
| 1 | +/** |
| 2 | + * Finds unnecessary usage of `Objects.deepEquals`. That method is mainly intended for |
| 3 | + * `Object[]` or multi-dimensional arrays. For all other cases this method is not |
| 4 | + * needed and there are other ways to check for equality, which also make the |
| 5 | + * intention clearer: |
| 6 | + * - If both arguments are primitive arrays, use one of the `Arrays.equals` methods, |
| 7 | + * such as `Arrays.equals(int[], int[])` |
| 8 | + * - If both arguments are one-dimensional arrays with component type other than `Object`, |
| 9 | + * use `Arrays.equals(Object[], Object[])` |
| 10 | + * - Otherwise use `Objects.equals(Object, Object)` if the arguments can be `null`, |
| 11 | + * or if not directly call `equals` on one of the arguments |
| 12 | + * |
| 13 | + * @kind problem |
| 14 | + */ |
| 15 | + |
| 16 | +import java |
| 17 | + |
| 18 | +class DeepEqualsMethod extends Method { |
| 19 | + DeepEqualsMethod() { |
| 20 | + getDeclaringType().hasQualifiedName("java.util", "Objects") |
| 21 | + and hasName("deepEquals") |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +from MethodAccess deepEqualsCall, Expr nonObjectArrayArg, Type argType |
| 26 | +where |
| 27 | + deepEqualsCall.getMethod() instanceof DeepEqualsMethod |
| 28 | + and nonObjectArrayArg = deepEqualsCall.getAnArgument() |
| 29 | + and argType = nonObjectArrayArg.getType() |
| 30 | + and not ( |
| 31 | + argType instanceof TypeObject |
| 32 | + // Object[] |
| 33 | + or argType.(Array).getComponentType() instanceof TypeObject |
| 34 | + // Multi-dimensional array |
| 35 | + or argType.(Array).getComponentType() instanceof Array |
| 36 | + ) |
| 37 | +select deepEqualsCall, "Unnecessary usage of `Objects.deepEquals` because $@ has neither type `Object` nor `Object[]`, nor is it a multi-dimensional array", |
| 38 | + nonObjectArrayArg, "this argument" |
0 commit comments