为什么 Google 先决条件库中的跳棋采用对象而不是字符串

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

为什么 Google Precondition 库中的 check* 方法采用对象而不是字符串?我可以看到该对象被称为 String.valueOf() 。我认为这种设计是由于没有代表客户做出任何假设。但是我想不出一个合理的情况,客户端会用字符串以外的任何东西来调用它。

我想客户可以传递一个实现了 toString() 方法的对象。但是你能举一个真实世界的例子来说明如何使用它/你一直在使用它吗?

Why does check* methods in Google Precondition library take an Object instead of a String?

性能。如果我有一个对象还不是 String,尤其是 toString() 是一种昂贵方法的对象,那么:

checkArgument(valid, obj.toString());

将无条件调用 toString() 并立即丢弃结果。另一方面:

checkArgument(valid, obj);

可以推迟该调用。由于预计检查会成功,因此延迟可以避免浪费。

这与使用日志格式而不是传递连接字符串 (Logger slf4j advantages of formatting with {} instead of string concatenation) 的原因相同。

同意 Joe 的观点并补充:空值处理。

查看方法签名:checkArgument(boolean expression, @Nullable Object errorMessage)