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.Preconditions.format;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021import com.google.errorprone.annotations.CanIgnoreReturnValue;
022import javax.annotation.Nullable;
023
024/**
025 * Static convenience methods that serve the same purpose as Java language
026 * <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html">
027 * assertions</a>, except that they are always enabled. These methods should be used instead of Java
028 * assertions whenever there is a chance the check may fail "in real life". Example: <pre>   {@code
029 *
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());}</pre>
035 *
036 * <h3>Comparison to alternatives</h3>
037 *
038 * <p><b>Note:</b> In some cases the differences explained below can be subtle. When it's unclear
039 * which approach to use, <b>don't worry</b> too much about it; just pick something that seems
040 * reasonable and it will be fine.
041 *
042 * <ul>
043 * <li>If checking whether the <i>caller</i> has violated your method or constructor's contract
044 *     (such as by passing an invalid argument), use the utilities of the {@link Preconditions}
045 *     class instead.
046 *
047 * <li>If checking an <i>impossible</i> condition (which <i>cannot</i> happen unless your own class
048 *     or its <i>trusted</i> dependencies is badly broken), this is what ordinary Java assertions
049 *     are for. Note that assertions are not enabled by default; they are essentially considered
050 *     "compiled comments."
051 *
052 * <li>An explicit {@code if/throw} (as illustrated below) is always acceptable; we still recommend
053 *     using our {@link VerifyException} exception type. Throwing a plain {@link RuntimeException}
054 *     is frowned upon.
055 *
056 * <li>Use of {@link java.util.Objects#requireNonNull(Object)} is generally discouraged, since
057 *     {@link #verifyNotNull(Object)} and {@link Preconditions#checkNotNull(Object)} perform the
058 *     same function with more clarity.
059 * </ul>
060 *
061 * <h3>Warning about performance</h3>
062 *
063 * <p>Remember that parameter values for message construction must all be computed eagerly, and
064 * autoboxing and varargs array creation may happen as well, even when the verification succeeds and
065 * the message ends up unneeded. Performance-sensitive verification checks should continue to use
066 * usual form: <pre>   {@code
067 *
068 *   Bill bill = remoteService.getLastUnpaidBill();
069 *   if (bill.status() != Status.UNPAID) {
070 *     throw new VerifyException("Unexpected bill status: " + bill.status());
071 *   }}</pre>
072 *
073 * <h3>Only {@code %s} is supported</h3>
074 *
075 * <p>As with {@link Preconditions} error message template strings, only the {@code "%s"} specifier
076 * is supported, not the full range of {@link java.util.Formatter} specifiers. However, note that if
077 * the number of arguments does not match the number of occurrences of {@code "%s"} in the format
078 * string, {@code Verify} will still behave as expected, and will still include all argument values
079 * in the error message; the message will simply not be formatted exactly as intended.
080 *
081 * <h3>More information</h3>
082 *
083 * See <a href="https://github.com/google/guava/wiki/ConditionalFailuresExplained">Conditional
084 * failures explained</a> in the Guava User Guide for advice on when this class should be used.
085 *
086 * @since 17.0
087 */
088@Beta
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
112   *     {@code errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted
113   *     message in 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      @Nullable String errorMessageTemplate,
122      @Nullable Object... errorMessageArgs) {
123    if (!expression) {
124      throw new VerifyException(format(errorMessageTemplate, errorMessageArgs));
125    }
126  }
127
128  /**
129   * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a default
130   * message otherwise.
131   *
132   * @return {@code reference}, guaranteed to be non-null, for convenience
133   * @throws VerifyException if {@code reference} is {@code null}
134   * @see Preconditions#checkNotNull Preconditions.checkNotNull()
135   */
136  @CanIgnoreReturnValue
137  public static <T> T verifyNotNull(@Nullable T reference) {
138    return verifyNotNull(reference, "expected a non-null reference");
139  }
140
141  /**
142   * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a custom
143   * message otherwise.
144   *
145   * @param errorMessageTemplate a template for the exception message should the check fail. The
146   *     message is formed by replacing each {@code %s} placeholder in the template with an
147   *     argument. These are matched by position - the first {@code %s} gets
148   *     {@code errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted
149   *     message in square braces. Unmatched placeholders will be left as-is.
150   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
151   *     are converted to strings using {@link String#valueOf(Object)}.
152   * @return {@code reference}, guaranteed to be non-null, for convenience
153   * @throws VerifyException if {@code reference} is {@code null}
154   * @see Preconditions#checkNotNull Preconditions.checkNotNull()
155   */
156  @CanIgnoreReturnValue
157  public static <T> T verifyNotNull(
158      @Nullable T reference,
159      @Nullable String errorMessageTemplate,
160      @Nullable Object... errorMessageArgs) {
161    verify(reference != null, errorMessageTemplate, errorMessageArgs);
162    return reference;
163  }
164
165  // TODO(kevinb): consider <T> T verifySingleton(Iterable<T>) to take over for
166  // Iterables.getOnlyElement()
167
168  private Verify() {}
169}