4

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?

Nilanjan Basu
  • 828
  • 9
  • 20

2 Answers2

7

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

Community
  • 1
  • 1
Joe
  • 29,416
  • 12
  • 68
  • 88
1

Agree with Joe and plus: null handling.

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

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130