Why does check* methods in Google Precondition library take an Object instead of a String? I can see that the object is called String.valueOf() on. I think this design was due to not making any assumption on behalf of the client. But I cannot think about a reasonable case where client will be calling this with anything other than a String.
I guess clients could pass an object that has implemented a toString() method. But can you give a real world example on how this can be used/ you have been using this?
Why does check* methods in Google Precondition library take an Object instead of a String?
Performance. If I have an object that is not already a String
, particularly one where toString()
is an expensive method, then:
checkArgument(valid, obj.toString());
will unconditionally call toString()
and immediately discard the result. On the other hand:
checkArgument(valid, obj);
can defer that invocation. Since the check is expected to succeed, that deferral avoids waste.
This is the same reason for using log formatting instead of passing a concatenated string (Logger slf4j advantages of formatting with {} instead of string concatenation).
Agree with Joe and plus: null handling.
See the method signature: checkArgument(boolean expression, @Nullable Object errorMessage)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With