001/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*-
002 *
003 * Copyright © 2025 microBean™.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
006 * the License. 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 distributed under the License is distributed on
011 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
012 * specific language governing permissions and limitations under the License.
013 */
014package org.microbean.bean;
015
016import java.util.Iterator;
017
018/**
019 * An {@link Iterable} {@linkplain #iterator() providing access to contextual references of a given type}, and a {@link
020 * ReferencesSelector} providing access to a {@link References} of a different type.
021 *
022 * @param <R> the contextual reference type
023 *
024 * @author <a href="https://about.me/lairdnelson" target="_top">Laird Nelson</a>
025 *
026 * @see ReferencesSelector
027 */
028public interface References<R> extends Iterable<R>, ReferencesSelector {
029
030  /**
031   * A convenience method that acquires and returns what is presumed, possibly incorrectly, to be the sole contextual
032   * reference available from this {@link References}.
033   *
034   * @return a contextual reference; never {@code null}
035   *
036   * @exception UnsatisfiedReductionException if there are no contextual references
037   *
038   * @exception AmbiguousReductionException if there is more than one contextual reference
039   */
040  public default R get() {
041    final Iterator<R> i = this.iterator();
042    if (!i.hasNext()) {
043      throw new UnsatisfiedReductionException(null, null, null);
044    }
045    final R r = i.next();
046    if (i.hasNext()) {
047      throw new AmbiguousReductionException(null, null, null);
048    }
049    return r;
050  }
051
052  /**
053   * Destroys the supplied contextual reference if and only if it meets the conditions for destruction.
054   *
055   * @param r a contextual reference; may be {@code null} in which case {@code false} will be returned
056   *
057   * @return {@code true} if and only if destruction occurred
058   *
059   * @exception DestructionException if an error occurs
060   */
061  public boolean destroy(final R r); // e.g. CDI's Instances#destroy(Object); works only on @Dependent objects
062
063}