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    
017    package com.google.common.collect;
018    
019    import com.google.common.annotations.Beta;
020    import com.google.common.annotations.GwtCompatible;
021    
022    /**
023     * A constraint that an element must satisfy in order to be added to a
024     * collection. For example, {@link Constraints#notNull()}, which prevents a
025     * collection from including any null elements, could be implemented like this:
026     * <pre>   {@code
027     *
028     *   public Object checkElement(Object element) {
029     *     if (element == null) {
030     *       throw new NullPointerException();
031     *     }
032     *     return element;
033     *   }}</pre>
034     *
035     * In order to be effective, constraints should be deterministic; that is,
036     * they should not depend on state that can change (such as external state,
037     * random variables, and time) and should only depend on the value of the
038     * passed-in element. A non-deterministic constraint cannot reliably enforce
039     * that all the collection's elements meet the constraint, since the constraint
040     * is only enforced when elements are added.
041     *
042     * @see Constraints
043     * @see MapConstraint
044     * @author Mike Bostock
045     * @since 3
046     */
047    @Beta
048    @GwtCompatible
049    public interface Constraint<E> {
050      /**
051       * Throws a suitable {@code RuntimeException} if the specified element is
052       * illegal. Typically this is either a {@link NullPointerException}, an
053       * {@link IllegalArgumentException}, or a {@link ClassCastException}, though
054       * an application-specific exception class may be used if appropriate.
055       *
056       * @param element the element to check
057       * @return the provided element
058       */
059      E checkElement(E element);
060    
061      /**
062       * Returns a brief human readable description of this constraint, such as
063       * "Not null" or "Positive number".
064       */
065      @Override
066      String toString();
067    }