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 javax.annotation.Nullable;
022
023/**
024 * A constraint on the keys and values that may be added to a {@code Map} or {@code Multimap}. For
025 * example, to prevent a map from including any null keys or values, you could implement a {@link
026 * MapConstraint} like this:
027 *
028 * <pre>{@code
029 * public void checkKeyValue(Object key, Object value) {
030 *   if (key == null || value == null) {
031 *     throw new NullPointerException();
032 *   }
033 * }
034 * }</pre>
035 *
036 * <p>In order to be effective, constraints should be deterministic; that is, they should not depend
037 * on state that can change (such as external state, random variables, and time) and should only
038 * depend on the value of the passed-in key and value. A non-deterministic constraint cannot
039 * reliably enforce that all the collection's elements meet the constraint, since the constraint is
040 * only enforced when elements are added.
041 *
042 * @author Mike Bostock
043 * @see MapConstraints
044 * @see Constraint
045 * @since 3.0
046 * @deprecated Use {@link Preconditions} for basic checks. In place of constrained maps, we
047 *     encourage you to check your preconditions explicitly instead of leaving that work to the map
048 *     implementation. For the specific case of rejecting null, consider {@link ImmutableMap}. This
049 *     class is scheduled for removal in Guava 21.0.
050 */
051@GwtCompatible
052@Beta
053@Deprecated
054public interface MapConstraint<K, V> {
055  /**
056   * Throws a suitable {@code RuntimeException} if the specified key or value is
057   * illegal. Typically this is either a {@link NullPointerException}, an
058   * {@link IllegalArgumentException}, or a {@link ClassCastException}, though
059   * an application-specific exception class may be used if appropriate.
060   */
061  void checkKeyValue(@Nullable K key, @Nullable V value);
062
063  /**
064   * Returns a brief human readable description of this constraint, such as
065   * "Not null".
066   */
067  @Override
068  String toString();
069}