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;
021
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 above) 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
077 * if the number of arguments does not match the number of occurrences of {@code "%s"} in the
078 * format string, {@code Verify} will still behave as expected, and will still include all argument
079 * values in the error message; the message will simply not be formatted exactly as intended.
080 *
081 * <h3>More information</h3>
082 *
083 * See
084 * <a href="http://code.google.com/p/guava-libraries/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@Beta
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  public static void verify(boolean expression) {
097    if (!expression) {
098      throw new VerifyException();
099    }
100  }
101
102  /**
103   * Ensures that {@code expression} is {@code true}, throwing a {@code VerifyException} with a
104   * custom message otherwise.
105   *
106   * @param expression a boolean expression
107   * @param errorMessageTemplate a template for the exception message should the
108   *     check fail. The message is formed by replacing each {@code %s}
109   *     placeholder in the template with an argument. These are matched by
110   *     position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
111   *     Unmatched arguments will be appended to the formatted message in square
112   *     braces. Unmatched placeholders will be left as-is.
113   * @param errorMessageArgs the arguments to be substituted into the message
114   *     template. Arguments are converted to strings using
115   *     {@link String#valueOf(Object)}.
116   * @throws VerifyException if {@code expression} is {@code false}
117   */
118  public static void verify(
119      boolean expression,
120      @Nullable String errorMessageTemplate,
121      @Nullable Object... errorMessageArgs) {
122    if (!expression) {
123      throw new VerifyException(format(errorMessageTemplate, errorMessageArgs));
124    }
125  }
126
127  /**
128   * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a default
129   * message otherwise.
130   *
131   * @return {@code reference}, guaranteed to be non-null, for convenience
132   */
133  public static <T> T verifyNotNull(@Nullable T reference) {
134    return verifyNotNull(reference, "expected a non-null reference");
135  }
136
137  /**
138   * Ensures that {@code reference} is non-null, throwing a {@code VerifyException} with a custom
139   * message otherwise.
140   *
141   * @param errorMessageTemplate a template for the exception message should the
142   *     check fail. The message is formed by replacing each {@code %s}
143   *     placeholder in the template with an argument. These are matched by
144   *     position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
145   *     Unmatched arguments will be appended to the formatted message in square
146   *     braces. Unmatched placeholders will be left as-is.
147   * @param errorMessageArgs the arguments to be substituted into the message
148   *     template. Arguments are converted to strings using
149   *     {@link String#valueOf(Object)}.
150   * @return {@code reference}, guaranteed to be non-null, for convenience
151   */
152  public static <T> T verifyNotNull(
153      @Nullable T reference,
154      @Nullable String errorMessageTemplate,
155      @Nullable Object... errorMessageArgs) {
156    verify(reference != null, errorMessageTemplate, errorMessageArgs);
157    return reference;
158  }
159
160  // TODO(kevinb): consider <T> T verifySingleton(Iterable<T>) to take over for
161  // Iterables.getOnlyElement()
162
163  private Verify() {}
164}