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