kotlin——减少if的使用和嵌套、完美的登录校验、Map存储某个函数、三元

1、使用三元运算符

三元运算符减少if的嵌套

var a = if (true) 1 else 0  
private var token: String = when {
        !isNullOrEmpty(SharedPreferencesUtil.getSPInstance().getUseBean()?.data?.token) ->
            SharedPreferencesUtil.getSPInstance().getUseBean()?.data?.token!!
        else -> ""
    }
封装一个三元运算
inline fun <T> Boolean.then(trueValue: T, falseValue: T): T {
    return if (this) trueValue else falseValue
}

使用

val isEven = 4 % 2 == 0
val result = isEven.then("Even", "Odd")
println(result)  // 输出: Even

2、使用when

when {
            mainViewModel.mUserModel.username.get()!!.isEmpty() -> show("用户名不可以为空")
            mainViewModel.mUserModel.password.get()!!.isEmpty() -> show("密码不可以为空")
            else -> mainViewModel.login()
        }

完美的登录校验

when {
            mainViewModel.mUserModel.username.get()!!.isEmpty() -> usernameLayout.error = "用户名不可以为空"
            mainViewModel.mUserModel.password.get()!!.isEmpty() -> passwordLayout.error = "密码不可以为空"
            else -> {
                usernameLayout.isErrorEnabled = false // 红色提示去掉
                passwordLayout.isErrorEnabled = false // 红色提示去掉
                mainViewModel.login()
            }

        }

具体请看:kotlin-Mvvm-双向绑定-登录-减少ifelse-Android文档类资源-优快云下载

3、提前判断返回

如下语句

if(condition){ 
    //dost
}else{ 
    return ;
}

改为

if(!condition){ 
    return ;
}
//dost

避免一些不必要的分支,让代码更精炼。

4、数组的形式去除if

优化前:

fun getDays(month: Int): Int {
        if (month == 1) return 31
        if (month == 2) return 29
        if (month == 3) return 31
        if (month == 4) return 30
        if (month == 5) return 31
        if (month == 6) return 30
        if (month == 7) return 31
        if (month == 8) return 31
        if (month == 9) return 30
        if (month == 10) return 31
        if (month == 11) return 30
        if (month == 12) return 31
        return 0
    }

优化后:

fun getDaysOpt(month: Int): Int {
        var monthDays = intArrayOf(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
        return monthDays[month]
    }

5、表驱动(Map存储某个函数)

优化前

//优化前
    fun getDays(param: Int) {
        if (param.equals(1)) {
            doAction1(10)
        } else if (param.equals(5)) {
            doAction2(20)
        } else if (param.equals(10)) {
            doAction3(30)
        }
    }

优化后

//优化后
    fun getDaysOpt(param: Int) {
        val actionMappings: Map<Any, () -> Unit> = hashMapOf(
            1 to { doAction1(10) },
            5 to { doAction2(20) },
            10 to { doAction3(30) }
        )
        actionMappings[param]?.invoke()
    }

    fun doAction1(param: Int) {
        println("doAction1:" + param)
    }

    fun doAction2(param: Int) {
        println("doAction2:" + param)
    }

    fun doAction3(param: Int) {
        println("doAction3:" + param)
    }

6、使用Optional或者?. 来进行优化

使用,代码如下:

// 原来的代码
return if (order == null) {
            "-1"
        } else {
            order.take(3) // 获取前三个字符
        }


// 使用Optional优化后的代码
return Optional.ofNullable(order).map { o -> o.take(3) }.orElse("-1")


// 使用kotlin语法优化
return order?.take(3)?: "-1" // 获取前三个字符

7、使用takeIf减少嵌套

原始代码为:

errorMsgFrag?.apply {
    if (isHidden){
        errorMsgFrag?.show(supportFragmentManager, “ErrorMsgFrag”)
    }
}

 优化后的代码:

errorMsgFrag?.takeIf { it.isHidden }?.let {
    it.show(supportFragmentManager, "ErrorMsgFrag")
}

8、策略模式 + 工厂方法  减少if

    interface Strategy {
        fun executeStrategy(): String
    }

    class StrategyA : Strategy {
        override fun executeStrategy(): String {
            return "执行策略A"
        }
    }

    class StrategyB : Strategy {
        override fun executeStrategy(): String {
            return "执行策略B"
        }
    }
    object StrategyFactory {
        fun createStrategy(condition: Int): Strategy {
            return when (condition) {
                1 -> StrategyA()
                2 -> StrategyB()
                else -> throw IllegalArgumentException("无效的条件")
            }
        }
    }
    // 使用示例
    fun main() {
        val strategy = StrategyFactory.createStrategy(1)
        val result = strategy.executeStrategy()
        println(result)
    }

9、 使用数组的方式减少if

有一个参数,如果该值为空,就依次取几个备用参数的值,如果几个备用的参数都为空,最后取默认值

String info = xx.getInfo();
if (info == null) {
    info = xx.getInfo1();
    if (info == null) {
        info = xx.getInfo2();
        if (info == null) {
            info = xx.getInfo3();
            if (info == null) {
                info = xx.getInfo4();
                if (info == null) {
                    info = "Java技术栈(默认)";
                }
            }
        }
    }
}

 优化后的代码:

List<String> list = new ArrayList<>(Arrays.asList(info, info1, info2, info3, info4, "Java技术栈(默认)"));
list.removeIf(StringUtils::isBlank);
String result = list.get(0);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wy313622821

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值