Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does Checkers in Google Precondition Library take object in stead of a String

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?

like image 233
Nilanjan Basu Avatar asked Feb 10 '23 23:02

Nilanjan Basu


2 Answers

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).

like image 66
Joe Avatar answered Feb 13 '23 22:02

Joe


Agree with Joe and plus: null handling.

See the method signature: checkArgument(boolean expression, @Nullable Object errorMessage)

like image 31
卢声远 Shengyuan Lu Avatar answered Feb 13 '23 20:02

卢声远 Shengyuan Lu