001/*
002 * Copyright (C) 2013 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Strings.lenientFormat;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.errorprone.annotations.CanIgnoreReturnValue;
021import org.jspecify.annotations.Nullable;
022
023/**
024 * Static convenience methods that serve the same purpose as Java language <a
025 * href="https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html">assertions</a>,
026 * except that they are always enabled. These methods should be used instead of Java assertions
027 * whenever there is a chance the check may fail "in real life". Example:
028 *
029 * {@snippet :
030 * Bill bill = remoteService.getLastUnpaidBill();
031 *
032 * // In case bug 12345 happens again we'd rather just die
033 * Verify.verify(bill.status() == Status.UNPAID,
034 *     "Unexpected bill status: %s", bill.status());
035 * }
036 *
037 * <h2>Comparison to alternatives</h2>
038 *
039 * <p><b>Note:</b> In some cases the differences explained below can be subtle. When it's unclear
040 * which approach to use, <b>don't worry</b> too much about it; just pick something that seems
041 * reasonable and it will be fine.
042 *
043 * <ul>
044 *   <li>If checking whether the <i>caller</i> has violated your method or constructor's contract
045 *       (such as by passing an invalid argument), use the utilities of the {@link Preconditions}
046 *       class instead.
047 *   <li>If checking an <i>impossible</i> condition (which <i>cannot</i> happen unless your own
048 *       class or its <i>trusted</i> dependencies are badly broken), this is what ordinary Java
049 *       assertions are for. Note that assertions are not enabled by default; they are essentially
050 *       considered "compiled comments."
051 *   <li>An explicit {@code if/throw} (as illustrated below) is always acceptable; we still
052 *       recommend using our {@link VerifyException} exception type. Throwing a plain {@link
053 *       RuntimeException} is frowned upon.
054 *   <li>Use of {@link java.util.Objects#requireNonNull(Object)} is generally discouraged, since
055 *       {@link #verifyNotNull(Object)} and {@link Preconditions#checkNotNull(Object)} perform the
056 *       same function with more clarity.
057 * </ul>
058 *
059 * <h2>Warning about performance</h2>
060 *
061 * <p>Remember that parameter values for message construction must all be computed eagerly, and
062 * autoboxing and varargs array creation may happen as well, even when the verification succeeds and
063 * the message ends up unneeded. Performance-sensitive verification checks should continue to use
064 * usual form:
065 *
066 * {@snippet :
067 * Bill bill = remoteService.getLastUnpaidBill();
068 * if (bill.status() != Status.UNPAID) {
069 *   throw new VerifyException("Unexpected bill status: " + bill.status());
070 * }
071 * }
072 *
073 * <h2>Only {@code %s} is supported</h2>
074 *
075 * <p>As with {@link Preconditions}, {@code Verify} uses {@link Strings#lenientFormat} to format
076 * error message template strings. This only supports the {@code "%s"} specifier, not the full range
077 * of {@link java.util.Formatter} specifiers. However, note that if the number of arguments does not
078 * match the number of occurrences of {@code "%s"} in the format string, {@code Verify} will still
079 * behave as expected, and will still include all argument values in the error message; the message
080 * will simply not be formatted exactly as intended.
081 *
082 * <h2>More information</h2>
083 *
084 * See <a href="https://github.com/google/guava/wiki/ConditionalFailuresExplained">Conditional
085 * failures explained</a> in the Guava User Guide for advice on when this class should be used.
086 *
087 * @since 17.0
088 */
089@GwtCompatible
090public final class Verify {
091  /**
092   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with no
093   * message otherwise.
094   *
095   * @throws VerifyException if {@code expression} is {@code false}
096   * @see Preconditions#checkState Preconditions.checkState()
097   */
098  public static void verify(boolean expression) {
099    if (!expression) {
100      throw new VerifyException();
101    }
102  }
103
104  /**
105   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
106   * custom message otherwise.
107   *
108   * @param expression a boolean expression
109   * @param errorMessageTemplate a template for the exception message should the check fail. The
110   *     message is formed by replacing each {@code %s} placeholder in the template with an
111   *     argument. These are matched by position - the first {@code %s} gets {@code
112   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
113   *     square braces. Unmatched placeholders will be left as-is.
114   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
115   *     are converted to strings using {@link String#valueOf(Object)}.
116   * @throws VerifyException if {@code expression} is {@code false}
117   * @see Preconditions#checkState Preconditions.checkState()
118   */
119  public static void verify(
120      boolean expression,
121      String errorMessageTemplate,
122      @Nullable Object @Nullable ... errorMessageArgs) {
123    if (!expression) {
124      throw new VerifyException(lenientFormat(errorMessageTemplate, errorMessageArgs));
125    }
126  }
127
128  /**
129   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
130   * custom message otherwise.
131   *
132   * <p>See {@link #verify(boolean, String, Object...)} for details.
133   *
134   * @since 23.1 (varargs overload since 17.0)
135   */
136  public static void verify(
137      boolean expression, String errorMessageTemplate, char p1) {
138    if (!expression) {
139      throw new VerifyException(lenientFormat(errorMessageTemplate, p1));
140    }
141  }
142
143  /**
144   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
145   * custom message otherwise.
146   *
147   * <p>See {@link #verify(boolean, String, Object...)} for details.
148   *
149   * @since 23.1 (varargs overload since 17.0)
150   */
151  public static void verify(
152      boolean expression, String errorMessageTemplate, int p1) {
153    if (!expression) {
154      throw new VerifyException(lenientFormat(errorMessageTemplate, p1));
155    }
156  }
157
158  /**
159   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
160   * custom message otherwise.
161   *
162   * <p>See {@link #verify(boolean, String, Object...)} for details.
163   *
164   * @since 23.1 (varargs overload since 17.0)
165   */
166  public static void verify(
167      boolean expression, String errorMessageTemplate, long p1) {
168    if (!expression) {
169      throw new VerifyException(lenientFormat(errorMessageTemplate, p1));
170    }
171  }
172
173  /**
174   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
175   * custom message otherwise.
176   *
177   * <p>See {@link #verify(boolean, String, Object...)} for details.
178   *
179   * @since 23.1 (varargs overload since 17.0)
180   */
181  public static void verify(
182      boolean expression, String errorMessageTemplate, @Nullable Object p1) {
183    if (!expression) {
184      throw new VerifyException(lenientFormat(errorMessageTemplate, p1));
185    }
186  }
187
188  /**
189   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
190   * custom message otherwise.
191   *
192   * <p>See {@link #verify(boolean, String, Object...)} for details.
193   *
194   * @since 23.1 (varargs overload since 17.0)
195   */
196  public static void verify(
197      boolean expression, String errorMessageTemplate, char p1, char p2) {
198    if (!expression) {
199      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
200    }
201  }
202
203  /**
204   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
205   * custom message otherwise.
206   *
207   * <p>See {@link #verify(boolean, String, Object...)} for details.
208   *
209   * @since 23.1 (varargs overload since 17.0)
210   */
211  public static void verify(
212      boolean expression, String errorMessageTemplate, int p1, char p2) {
213    if (!expression) {
214      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
215    }
216  }
217
218  /**
219   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
220   * custom message otherwise.
221   *
222   * <p>See {@link #verify(boolean, String, Object...)} for details.
223   *
224   * @since 23.1 (varargs overload since 17.0)
225   */
226  public static void verify(
227      boolean expression, String errorMessageTemplate, long p1, char p2) {
228    if (!expression) {
229      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
230    }
231  }
232
233  /**
234   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
235   * custom message otherwise.
236   *
237   * <p>See {@link #verify(boolean, String, Object...)} for details.
238   *
239   * @since 23.1 (varargs overload since 17.0)
240   */
241  public static void verify(
242      boolean expression,
243      String errorMessageTemplate,
244      @Nullable Object p1,
245      char p2) {
246    if (!expression) {
247      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
248    }
249  }
250
251  /**
252   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
253   * custom message otherwise.
254   *
255   * <p>See {@link #verify(boolean, String, Object...)} for details.
256   *
257   * @since 23.1 (varargs overload since 17.0)
258   */
259  public static void verify(
260      boolean expression, String errorMessageTemplate, char p1, int p2) {
261    if (!expression) {
262      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
263    }
264  }
265
266  /**
267   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
268   * custom message otherwise.
269   *
270   * <p>See {@link #verify(boolean, String, Object...)} for details.
271   *
272   * @since 23.1 (varargs overload since 17.0)
273   */
274  public static void verify(
275      boolean expression, String errorMessageTemplate, int p1, int p2) {
276    if (!expression) {
277      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
278    }
279  }
280
281  /**
282   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
283   * custom message otherwise.
284   *
285   * <p>See {@link #verify(boolean, String, Object...)} for details.
286   *
287   * @since 23.1 (varargs overload since 17.0)
288   */
289  public static void verify(
290      boolean expression, String errorMessageTemplate, long p1, int p2) {
291    if (!expression) {
292      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
293    }
294  }
295
296  /**
297   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
298   * custom message otherwise.
299   *
300   * <p>See {@link #verify(boolean, String, Object...)} for details.
301   *
302   * @since 23.1 (varargs overload since 17.0)
303   */
304  public static void verify(
305      boolean expression,
306      String errorMessageTemplate,
307      @Nullable Object p1,
308      int p2) {
309    if (!expression) {
310      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
311    }
312  }
313
314  /**
315   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
316   * custom message otherwise.
317   *
318   * <p>See {@link #verify(boolean, String, Object...)} for details.
319   *
320   * @since 23.1 (varargs overload since 17.0)
321   */
322  public static void verify(
323      boolean expression, String errorMessageTemplate, char p1, long p2) {
324    if (!expression) {
325      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
326    }
327  }
328
329  /**
330   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
331   * custom message otherwise.
332   *
333   * <p>See {@link #verify(boolean, String, Object...)} for details.
334   *
335   * @since 23.1 (varargs overload since 17.0)
336   */
337  public static void verify(
338      boolean expression, String errorMessageTemplate, int p1, long p2) {
339    if (!expression) {
340      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
341    }
342  }
343
344  /**
345   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
346   * custom message otherwise.
347   *
348   * <p>See {@link #verify(boolean, String, Object...)} for details.
349   *
350   * @since 23.1 (varargs overload since 17.0)
351   */
352  public static void verify(
353      boolean expression, String errorMessageTemplate, long p1, long p2) {
354    if (!expression) {
355      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
356    }
357  }
358
359  /**
360   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
361   * custom message otherwise.
362   *
363   * <p>See {@link #verify(boolean, String, Object...)} for details.
364   *
365   * @since 23.1 (varargs overload since 17.0)
366   */
367  public static void verify(
368      boolean expression,
369      String errorMessageTemplate,
370      @Nullable Object p1,
371      long p2) {
372    if (!expression) {
373      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
374    }
375  }
376
377  /**
378   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
379   * custom message otherwise.
380   *
381   * <p>See {@link #verify(boolean, String, Object...)} for details.
382   *
383   * @since 23.1 (varargs overload since 17.0)
384   */
385  public static void verify(
386      boolean expression,
387      String errorMessageTemplate,
388      char p1,
389      @Nullable Object p2) {
390    if (!expression) {
391      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
392    }
393  }
394
395  /**
396   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
397   * custom message otherwise.
398   *
399   * <p>See {@link #verify(boolean, String, Object...)} for details.
400   *
401   * @since 23.1 (varargs overload since 17.0)
402   */
403  public static void verify(
404      boolean expression,
405      String errorMessageTemplate,
406      int p1,
407      @Nullable Object p2) {
408    if (!expression) {
409      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
410    }
411  }
412
413  /**
414   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
415   * custom message otherwise.
416   *
417   * <p>See {@link #verify(boolean, String, Object...)} for details.
418   *
419   * @since 23.1 (varargs overload since 17.0)
420   */
421  public static void verify(
422      boolean expression,
423      String errorMessageTemplate,
424      long p1,
425      @Nullable Object p2) {
426    if (!expression) {
427      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
428    }
429  }
430
431  /**
432   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
433   * custom message otherwise.
434   *
435   * <p>See {@link #verify(boolean, String, Object...)} for details.
436   *
437   * @since 23.1 (varargs overload since 17.0)
438   */
439  public static void verify(
440      boolean expression,
441      String errorMessageTemplate,
442      @Nullable Object p1,
443      @Nullable Object p2) {
444    if (!expression) {
445      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2));
446    }
447  }
448
449  /**
450   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
451   * custom message otherwise.
452   *
453   * <p>See {@link #verify(boolean, String, Object...)} for details.
454   *
455   * @since 23.1 (varargs overload since 17.0)
456   */
457  public static void verify(
458      boolean expression,
459      String errorMessageTemplate,
460      @Nullable Object p1,
461      @Nullable Object p2,
462      @Nullable Object p3) {
463    if (!expression) {
464      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2, p3));
465    }
466  }
467
468  /**
469   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
470   * custom message otherwise.
471   *
472   * <p>See {@link #verify(boolean, String, Object...)} for details.
473   *
474   * @since 23.1 (varargs overload since 17.0)
475   */
476  public static void verify(
477      boolean expression,
478      String errorMessageTemplate,
479      @Nullable Object p1,
480      @Nullable Object p2,
481      @Nullable Object p3,
482      @Nullable Object p4) {
483    if (!expression) {
484      throw new VerifyException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
485    }
486  }
487
488  /*
489   * For a discussion of the signature of verifyNotNull, see the discussion above
490   * Preconditions.checkNotNull.
491   *
492   * (verifyNotNull has many fewer "problem" callers, so we could try to be stricter. On the other
493   * hand, verifyNotNull arguably has more reason to accept nullable arguments in the first
494   * place....)
495   */
496
497  /**
498   * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a default
499   * message otherwise.
500   *
501   * @return {@code reference}, guaranteed to be non-null, for convenience
502   * @throws VerifyException if {@code reference} is {@code null}
503   * @see Preconditions#checkNotNull Preconditions.checkNotNull()
504   */
505  @CanIgnoreReturnValue
506  public static <T> T verifyNotNull(@Nullable T reference) {
507    return verifyNotNull(reference, "expected a non-null reference");
508  }
509
510  /**
511   * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a custom
512   * message otherwise.
513   *
514   * @param errorMessageTemplate a template for the exception message should the check fail. The
515   *     message is formed by replacing each {@code %s} placeholder in the template with an
516   *     argument. These are matched by position - the first {@code %s} gets {@code
517   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
518   *     square braces. Unmatched placeholders will be left as-is.
519   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
520   *     are converted to strings using {@link String#valueOf(Object)}.
521   * @return {@code reference}, guaranteed to be non-null, for convenience
522   * @throws VerifyException if {@code reference} is {@code null}
523   * @see Preconditions#checkNotNull Preconditions.checkNotNull()
524   */
525  @CanIgnoreReturnValue
526  public static <T> T verifyNotNull(
527      @Nullable T reference,
528      String errorMessageTemplate,
529      @Nullable Object @Nullable ... errorMessageArgs) {
530    if (reference == null) {
531      throw new VerifyException(lenientFormat(errorMessageTemplate, errorMessageArgs));
532    }
533    return reference;
534  }
535
536  // TODO(kevinb): consider <T> T verifySingleton(Iterable<T>) to take over for
537  // Iterables.getOnlyElement()
538
539  private Verify() {}
540}