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