Java 8 Optional单值容器的不合理实现?

为什么说JDK 8 Optional<T>的实现挺不合理的?因为Optional<T>值容器对“包含的值是否存在”是基于value != nullvalue == null判断的,而非基于isPresent()方法。这样实现的后果是很难做自定义扩展,如果要做扩展需要重新实现大部分接口。其基本数据类型的实现类OptionalInt,也是基于isPresent字段做判断条件,蓝瘦香菇。maybe他们就不想让我们做扩展,不然真想不出什么理由。public final class Optional<T>,final类😂😂😂。

扩展性设计贯穿在集合框架的抽象类实现中,核心集合接口的基础实现是全部基于抽象方法实现的。例如,AbstractCollection<E>AbstractList<E>

为什么会聊这个话题?因为我们在实际编程中都会通过HTTP请求调用他人的API,其成功/失败的返回一般都是基于返回码(code)来判断的,这时想基于Optional<T>做扩展,发现几乎要重新实现所有方法,很杯具😭。

下面是在JDK原有实现上,基于扩展性考虑修改的代码。如有哪里不合理的地方,感谢指出来。

// [函数式接口] 可能包含null值的容器对象
public final class Optional<T> {
    /**
     * Common instance for {@code empty()}.
     * 空实例({@linkplain #empty()})
     */
    private static final Optional<?> EMPTY = new Optional<>();

    /**
     * If non-null, the value; if null, indicates no value is present
     * null表示值不存在
     */
    private final T value;

    /**
     * Constructs an empty instance.
     *
     * @implNote Generally only one empty instance, {@link Optional#EMPTY},
     * should exist per VM.
     */
    private Optional() {
        this.value = null;
    }

    /**
     * Returns an empty {@code Optional} instance.  No value is present for this
     * Optional.
     *
     * @apiNote Though it may be tempting to do so, avoid testing if an object
     * is empty by comparing with {@code ==} against instances returned by
     * {@code Option.empty()}. There is no guarantee that it is a singleton.
     * Instead, use {@link #isPresent()}.
     *
     * @param <T> Type of the non-existent value
     * @return an empty {@code Optional}
     */
    // 核心方法 返回空实例
    public static<T> Optional<T> empty() {
        @SuppressWarnings("unchecked")
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
    }

    /**
     * Constructs an instance with the value present.
     *
     * @param value the non-null value to be present 存在的非null值
     * @throws NullPointerException if value is null
     */
    private Optional(T value) {
        this.value = Objects.requireNonNull(value); // 必须是非null值
    }

    /**
     * Returns an {@code Optional} with the specified present non-null value.
     *
     * @param <T> the class of the value 值的类型
     * @param value the value to be present, which must be non-null 存在的值,必须不是非null
     * @return an {@code Optional} with the value present
     * @throws NullPointerException if value is null 如果值是null,则抛出NPE
     */
    // 核心方法 返回一个指定存在的非空值的可选实例
    public static <T> Optional<T> of(T value) {
        return new Optional<>(value);
    }

    /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     *
     * @param <T> the class of the value 值的类型
     * @param value the possibly-null value to describe 描述可为null的值
     * @return an {@code Optional} with a present value if the specified value
     * is non-null, otherwise an empty {@code Optional}
     */
    // 核心方法 如果值非空,返回一个描述指定值的可选实例;否则,返回一个空实例
    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

    /**
     * If a value is present in this {@code Optional}, returns the value,
     * otherwise throws {@code NoSuchElementException}.
     *
     * @return the non-null value held by this {@code Optional}
     * @throws NoSuchElementException if there is no value present
     *
     * @see Optional#isPresent()
     */
    // 核心方法 如果值存在,则返回该值;否则,抛出没有这个元素异常
    public T get() {
//        if (value == null) {
        if (!isPresent()) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

    /**
     * Return {@code true} if there is a value present, otherwise {@code false}.
     *
     * @return {@code true} if there is a value present, otherwise {@code false}
     */
    // 核心方法 如果是存在的值,则返回true;否则,返回false
    public boolean isPresent() {
        return value != null;
    }

    // 函数式接口
    /**
     * If a value is present, invoke the specified consumer with the value,
     * otherwise do nothing.
     *
     * @param consumer block to be executed if a value is present
     * @throws NullPointerException if value is present and {@code consumer} is
     * null
     */
    // 核心方法 如果值是存在的,则调用指定的操作消费该值;否则,什么都不做
    public void ifPresent(Consumer<? super T> consumer) {
//        if (value != null)
        if (isPresent()) {
            consumer.accept(value);
        }
    }

    // 第一层:过滤
    /**
     * If a value is present, and the value matches the given predicate,
     * return an {@code Optional} describing the value, otherwise return an
     * empty {@code Optional}.
     *
     * @param predicate a predicate to apply to the value, if present
     * @return an {@code Optional} describing the value of this {@code Optional}
     * if a value is present and the value matches the given predicate,
     * otherwise an empty {@code Optional}
     * @throws NullPointerException if the predicate is null
     */
    // 核心方法 如果值是存在的,并且值匹配给定的谓词,则返回描述该值的可选实例;否则,返回空实例
    public Optional<T> filter(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate);
        if (!isPresent()) {
            return this;
        } else {
            return predicate.test(value) ? this : empty();
        }
    }

    // 使用规则:flatMap(mapper) { map(mapper) }
    /**
     * If a value is present, apply the provided mapping function to it,
     * and if the result is non-null, return an {@code Optional} describing the
     * result.  Otherwise return an empty {@code Optional}.
     *
     * @apiNote This method supports post-processing on optional values, without
     * the need to explicitly check for a return status.  For example, the
     * following code traverses a stream of file names, selects one that has
     * not yet been processed, and then opens that file, returning an
     * {@code Optional<FileInputStream>}:
     * <p>
     * 本方法支持可选值的后置处理,不需要显示地检查返回状态。
     * 例如,下面的代码遍历文件名称列表的流,选择一个尚未被处理的,然后打开该文件,并返回文件输出流的可选实例:
     *
     * <pre>{@code
     *     Optional<FileInputStream> fis =
     *         names.stream().filter(name -> !isProcessedYet(name))
     *                       .findFirst()
     *                       .map(name -> new FileInputStream(name));
     * }</pre>
     *
     * Here, {@code findFirst} returns an {@code Optional<String>}, and then
     * {@code map} returns an {@code Optional<FileInputStream>} for the desired
     * file if one exists.
     * <p>
     * {@code findFirst}返回一个字符串的可选实例,然后通过映射函数为存在的所需文件返回一个文件输入流的可选实例。
     *
     * @param <U> The type of the result of the mapping function 映射函数的结果类型
     * @param mapper a mapping function to apply to the value, if present 如果值存在,应用到值的映射函数
     * @return an {@code Optional} describing the result of applying a mapping
     * function to the value of this {@code Optional}, if a value is present,
     * otherwise an empty {@code Optional} 返回一个描述应用映射函数到该可选实例值的结果的可选实例
     * @throws NullPointerException if the mapping function is null
     */
    // 核心方法 如果值是存在的,则应用给定的映射函数,并且结果是非空的,则返回描述该结果的可选实例;否则,返回空实例
    public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent()) {
            return empty();
        } else {
            return Optional.ofNullable(mapper.apply(value)); // 映射结果可能为null,包装成Optional
        }
    }

    /**
     * If a value is present, apply the provided {@code Optional}-bearing
     * mapping function to it, return that result, otherwise return an empty
     * {@code Optional}.  This method is similar to {@link #map(Function)},
     * but the provided mapper is one whose result is already an {@code Optional},
     * and if invoked, {@code flatMap} does not wrap it with an additional
     * {@code Optional}.
     * <p>
     * 本方法和{@link #map(Function)}相似,但提供的映射函数的结果已是一个可选实例,
     * 如果被调用,本方法并不会使用一个额外的可选实例包装它。
     *
     * @param <U> The type parameter to the {@code Optional} returned by 返回的可选实例的类型参数
     * @param mapper a mapping function to apply to the value, if present
     *           the mapping function 应用到值的映射函数
     * @return the result of applying an {@code Optional}-bearing mapping
     * function to the value of this {@code Optional}, if a value is present,
     * otherwise an empty {@code Optional}
     * @throws NullPointerException if the mapping function is null or returns
     * a null result
     */
    // 核心方法 如果值是可选的,则应用提供的可选关系映射函数,然后返回该结果;否则,返回空实例
    public <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent()) {
            return empty();
        } else {
            return Objects.requireNonNull(mapper.apply(value)); // Optional<U>不能为null,原生返回
        }
    }

    /**
     * Return the value if present, otherwise return {@code other}.
     *
     * @param other the value to be returned if there is no value present, may
     * be null 可能为null
     * @return the value, if present, otherwise {@code other}
     */
    // 核心方法 如果值存在,则返回该值;否则,返回默认值
    public T orElse(T other) {
//        return value != null ? value : other;
        return isPresent() ? value : other;
    }

    /**
     * Return the value if present, otherwise invoke {@code other} and return
     * the result of that invocation.
     *
     * @param other a {@code Supplier} whose result is returned if no value
     * is present
     * @return the value if present otherwise the result of {@code other.get()}
     * @throws NullPointerException if value is not present and {@code other} is
     * null
     */
    // 核心方法 如果值存在,则返回该值;否则,调用结果提供者并返回调用的结果
    // 使用场景:数据多层保护设计,如Cache + DB
    public T orElseGet(Supplier<? extends T> other) {
//        return value != null ? value : other.get();
        return isPresent() ? value : other.get();
    }

    /**
     * Return the contained value, if present, otherwise throw an exception
     * to be created by the provided supplier.
     *
     * @apiNote A method reference to the exception constructor with an empty
     * argument list can be used as the supplier. For example,
     * {@code IllegalStateException::new}.
     * <p>
     * 一个引用使用空参数列表异常构造器的方法,可用于异常供应商。
     * 例如,{@code IllegalStateException::new}。
     *
     * @param <X> type of the exception to be thrown 待抛出的异常类型
     * @param exceptionSupplier The supplier which will return the exception to
     * be thrown 返回异常的供应商
     * @return the present value
     * @throws X if there is no value present
     * @throws NullPointerException if no value is present and
     * {@code exceptionSupplier} is null
     */
    // 核心方法 如果值存在,则返回包含的值;否则,抛出一个由提供的供应商创建的异常
    // 使用场景:基于异常的快速失败设计(fail-fast)
    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
//        if (value != null) {
        if (isPresent()) {
            return value;
        } else {
            throw exceptionSupplier.get(); // 值为null,则抛出异常
        }
    }


    // ----------------- Object -----------------
    /**
     * Indicates whether some other object is "equal to" this Optional. The
     * other object is considered equal if:
     * <ul>
     * <li>it is also an {@code Optional} and;
     * <li>both instances have no value present or;
     * <li>the present values are "equal to" each other via {@code equals()}.
     * </ul>
     *
     * @param obj an object to be tested for equality
     * @return {code true} if the other object is "equal to" this object
     * otherwise {@code false}
     */
    @Override
    public boolean equals(Object obj) {
        // 《Effective Java》总结的优化实现
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Optional)) {
            return false;
        }

        Optional<?> other = (Optional<?>) obj;
        return Objects.equals(value, other.value);
    }

    /**
     * Returns the hash code value of the present value, if any, or 0 (zero) if
     * no value is present.
     *
     * @return hash code value of the present value or 0 if no value is present
     */
    @Override
    public int hashCode() {
        return Objects.hashCode(value);
    }

    /**
     * Returns a non-empty string representation of this Optional suitable for
     * debugging. The exact presentation format is unspecified and may vary
     * between implementations and versions.
     *
     * @implSpec If a value is present the result must include its string
     * representation in the result. Empty and present Optionals must be
     * unambiguously differentiable.
     *
     * @return the string representation of this instance
     */
    @Override
    public String toString() {
//        return value != null
        return isPresent()
            ? String.format("Optional[%s]", value)
            : "Optional.empty"; // 空实例
    }
}

祝玩得开心!ˇˍˇ
云舒,2017.7.23,杭州

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,563评论 18 139
  • 一. Java基础部分.................................................
    wy_sure阅读 3,780评论 0 11
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,531评论 18 399
  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 4,251评论 0 16
  • java笔记第一天 == 和 equals ==比较的比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量...
    jmychou阅读 1,480评论 0 3