1/* 2 * Copyright (C) 2007 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.google.common.collect; 18 19import com.google.common.annotations.Beta; 20import com.google.common.annotations.GwtCompatible; 21 22/** 23 * A constraint that an element must satisfy in order to be added to a 24 * collection. For example, {@link Constraints#notNull()}, which prevents a 25 * collection from including any null elements, could be implemented like this: 26 * <pre> {@code 27 * 28 * public Object checkElement(Object element) { 29 * if (element == null) { 30 * throw new NullPointerException(); 31 * } 32 * return element; 33 * }}</pre> 34 * 35 * In order to be effective, constraints should be deterministic; that is, 36 * they should not depend on state that can change (such as external state, 37 * random variables, and time) and should only depend on the value of the 38 * passed-in element. A non-deterministic constraint cannot reliably enforce 39 * that all the collection's elements meet the constraint, since the constraint 40 * is only enforced when elements are added. 41 * 42 * @see Constraints 43 * @see MapConstraint 44 * @author Mike Bostock 45 * @since 3.0 46 */ 47@Beta 48@GwtCompatible 49public interface Constraint<E> { 50 /** 51 * Throws a suitable {@code RuntimeException} if the specified element is 52 * illegal. Typically this is either a {@link NullPointerException}, an 53 * {@link IllegalArgumentException}, or a {@link ClassCastException}, though 54 * an application-specific exception class may be used if appropriate. 55 * 56 * @param element the element to check 57 * @return the provided element 58 */ 59 E checkElement(E element); 60 61 /** 62 * Returns a brief human readable description of this constraint, such as 63 * "Not null" or "Positive number". 64 */ 65 @Override 66 String toString(); 67} 68