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