java函数式编程优雅的写if else

前言

我们在写业务代码的时候或多或少会写比较多的if else 进行判断抛出异常、分支处理等操作。这些if...else...充斥在代码中严重影响了代码代码的美观,这时我们可以利用java8的新特性来优雅的写if...else...

if if if 这种结构

原来的写法

String a= "aaa";

if (a.contains("a")) {
    System.out.println("a");
}
if (a.contains("b")) {
    System.out.println("b");
}
System.out.println(a);

现在的写法

BranchUtil.of(a)
        .chain()
        .match(s -> s.equals("bbb")).ifTrue(s -> System.err.println("222"))
        .match(s -> s.equals("aaa")).ifTrue(s -> System.err.println("333"))
        .orElse(s -> System.err.println(s));

if else if else if 这种结构

原来的写法

if (a.contains("aaa")) {
    System.out.println("1");
}else if (a.contains("aaa")) {
    System.out.println("2");
}else{
    throw new RuntimeException("未匹配到数据");
}

现在的写法

BranchUtil.of(a)
        .whenIf()
        .match(s -> s.equals("aaa")).ifTrue(s -> System.err.println("111"))
        .match(s -> s.equals("bbb")).ifTrue(s -> System.err.println("wwww"))
        .orElseThrow(() -> new RuntimeException("未匹配到数据"));

最后附上BranchUtil源码

package com.hellobike.moon.api.infrastructure.test;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class BranchUtil<T> {
    private T value;
    private Supplier fastSupplier;


    private static final BranchUtil<?> EMPTY = new BranchUtil<>();

    public static <T> BranchUtil<T> of(T value) {
        return new BranchUtil<>(value);
    }

    /**
     * 构建快速 if else 语义
     *
     * @param value
     * @return
     */
    public static BranchUtil<Boolean> ofBoolean(Boolean value) {
        return new BranchUtil<>(value);
    }

    public static <T> BranchUtil<T> of() {
        return new BranchUtil<>();
    }


    private BranchUtil(T value) {
        this();
        this.value = value;
    }

    private BranchUtil() {

    }

    /**
     *
     *
     * @return
     */
    public Chain<T> chain() {
        Chain<T> chain = new Chain<>();
        chain.value = this.value;
        return chain;
    }

    /**
     * If else 模式
     * if(true){
     *     return true;
     * }else{
     *     return false;
     * }
     *
     * @return
     */
    public IfOrElse<T> whenIf() {
        return new IfOrElse<>(value);
    }


    /**
     *
     *
     * @param thenGet
     * @return
     */
    public BranchUtil<Boolean> ifTrue(Supplier thenGet) {
        if ((Boolean) this.value) {
            this.fastSupplier = thenGet;
        }
        return (BranchUtil<Boolean>) this;
    }
    public Object orElse(Supplier orElseSupplier) {
        if (!(Boolean) this.value) {
            return orElseSupplier.get();
        }
        return fastSupplier.get();
    }

    /**
     * if(true){
     *      runnable.run();
     * }
     *
     * @param runnable
     */
    public void consumeTrue(Runnable runnable) {
        if ((Boolean) this.value) {
            runnable.run();
        }
    }


    /**
     * if(true){
     *     throw new RuntimeException
     * }
     *
     *
     * @param exceptionSupplier
     * @param <X>
     * @throws X
     */
    public <X extends Throwable> void thenThrow(Supplier<? extends X> exceptionSupplier) throws X {
        if ((Boolean) this.value) {
            throw exceptionSupplier.get();
        }
    }


    /**
     *
     * if if if 写法
     * @param <T>
     */
    public final class Chain<T> {

        private Supplier<Boolean> condition;
        private T value;
        private boolean hadMatch;

        public Chain<T> match(Predicate<T> predicate) {
            this.condition = () -> predicate.test(value);
            return this;
        }

        public Chain<T> ifTrue(Supplier resultSupplier) {
            if (checkCondition()) {
                hadMatch = true;
                resultSupplier.get();
            }
            return this;
        }

        public Chain<T> ifTrue(Consumer<T> resultConsume) {
            if (checkCondition()) {
                resultConsume.accept(value);
            }
            return this;
        }


        public boolean checkCondition() {
            return condition.get();
        }

        public void orElse(Supplier resultSupplier) {
            if (!hadMatch) {
                resultSupplier.get();
            }
        }

        public void orElse(Consumer<T> resultConsumer) {
            if (!hadMatch) {
                resultConsumer.accept(value);
            }
        }

    }

    /**
     * if else 模式
     *
     * @param <T>
     */
    public static final class IfOrElse<T> {
        private Supplier<Boolean> condition;
        private boolean hadMatch;

        private T value;
        private Object result;

        public IfOrElse(T value) {
            this.value = value;
        }

        public IfOrElse<T> match(Predicate<T> predicate) {
            this.condition = () -> predicate.test(value);
            return this;
        }


        public IfOrElse<T> ifTrue(Supplier resultSupplier) {
            //只允许匹配一次
            if (!hadMatch && condition.get()) {
                this.result = resultSupplier.get();
                hadMatch = true;
            }
            return this;
        }

        public IfOrElse<T> ifTrue(Consumer<T> resultConsume) {
            if (!hadMatch && condition.get()) {
                resultConsume.accept(value);
                hadMatch = true;
            }
            return this;
        }

        public <X extends Throwable> IfOrElse<T> orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
            if (result == null && !hadMatch) {
                throw exceptionSupplier.get();
            }
            return this;
        }

        public Object orElseGet(Supplier resultSupplier) {
            if (!hadMatch) {
                return resultSupplier.get();
            }
            return this.result;
        }

        public void orElse(Consumer<T> resultConsumer) {
            if (!hadMatch) {
                resultConsumer.accept(value);
            }
        }


    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值