001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.collect; 018 019import com.google.common.annotations.Beta; 020import com.google.common.annotations.GwtCompatible; 021import com.google.common.base.Preconditions; 022 023/** 024 * A constraint that an element must satisfy in order to be added to a 025 * collection. For example, {@link Constraints#notNull()}, which prevents a 026 * collection from including any null elements, could be implemented like this: 027 * <pre> {@code 028 * 029 * public Object checkElement(Object element) { 030 * if (element == null) { 031 * throw new NullPointerException(); 032 * } 033 * return element; 034 * }}</pre> 035 * 036 * <p>In order to be effective, constraints should be deterministic; that is, 037 * they should not depend on state that can change (such as external state, 038 * random variables, and time) and should only depend on the value of the 039 * passed-in element. A non-deterministic constraint cannot reliably enforce 040 * that all the collection's elements meet the constraint, since the constraint 041 * is only enforced when elements are added. 042 * 043 * @see Constraints 044 * @see MapConstraint 045 * @author Mike Bostock 046 * @since 3.0 047 * @deprecated Use {@link Preconditions} for basic checks. In place of 048 * constrained collections, we encourage you to check your preconditions 049 * explicitly instead of leaving that work to the collection implementation. 050 * For the specific case of rejecting null, consider the immutable 051 * collections. 052 * This interface is scheduled for removal in Guava 16.0. 053 */ 054@Beta 055@Deprecated 056@GwtCompatible 057public 058interface Constraint<E> { 059 /** 060 * Throws a suitable {@code RuntimeException} if the specified element is 061 * illegal. Typically this is either a {@link NullPointerException}, an 062 * {@link IllegalArgumentException}, or a {@link ClassCastException}, though 063 * an application-specific exception class may be used if appropriate. 064 * 065 * @param element the element to check 066 * @return the provided element 067 */ 068 E checkElement(E element); 069 070 /** 071 * Returns a brief human readable description of this constraint, such as 072 * "Not null" or "Positive number". 073 */ 074 @Override 075 String toString(); 076}