read(List<Object> keyValues)
read(..., ImmutableList<Object> keyValues, ...) {
// internally it calls: Key.of(value)
}
readWithComoundKeys(..., List<ImmutableList<Object>> compoundKeyValues, ...);
It’s very easy for clients to make mistake when call these methods. For example:
ImmutableList.of(ids)
creates a list with one element: the element is a List of all these ids:
As ImmutableList<List<String>>
is an ImmutableList of Object, so it compiles, but would fail at run time.
- Another problem in previous method is it uses ImmutableList which makes the method not able to take other Lists, we can just use List or Collection. ##### How General/Specific in parameter or return types?
- For parameters, use the most generic types possible
- For return types, use the most specific types possible This can be refactored as:
- This method can take a list of singular key or compound keys and much easier to use and not likely to make mistake.
of(Object ...)
public static SomeType of(Object... objects) {
for (Object object : objects) {
if (object instanceof String) {
} else if (object instanceof AnotherType) {
} else {
throw new IllegalArgumentException(...);
}
}
}
In most cases, this can be refactored as below:
public static SomeType of(List<String> objects) {}
public static SomeType of(List<AnotherType> objects) {}