• 请不要乱用Kotlin ? 空检查


    直接上实例:

    fun main(args: Array<String>) {
        println("now, begin save data to database")
        val dataBaseOperator: DataBaseOperator? = null
        dataBaseOperator?.saveDataToDataBase("important things")
        println("""return "ok" to other services""")
    }
    
    class DataBaseOperator {
    
        fun saveDataToDataBase(data: String) {
            println("save data $data to database")
        }
    }

    代码运行得完全没有问题,输出结果:

    now, begin save data to database
    return "ok" to other services

    But,很明显,我们的数据并没有保存到数据库中,但返回给了其他服务OK的结果,这个是要出大问题的。

    fun main(args: Array<String>) {
        println("now, begin save data to database")
        val dataBaseOperator: DataBaseOperator? = null
        // 错误做法
        //dataBaseOperator?.saveDataToDataBase("important things")
        // 正确做法
        dataBaseOperator!!.saveDataToDataBase("important things")
        println("""return "ok" to other services""")
    }

    正确的做法是直接抛出异常。因为数据库没有保存到数据库中,原因是null异常

    所以,一定不要为了保证代码运行得没有问题,而滥用 ? 。这样的做法是错误的。

    工程实例:

    @Controller
    class OrderController {
    
        val logger = LoggerFactory.getLogger(this.javaClass)
    
        @Autowired
        var orderService: PayOrderService? = null
    
        @PostMapping("payAliPay")
        @ResponseBody
        fun payAliPay(@RequestParam(value = "user_id", required = true) user_id: Long) {
            // 保存数据到数据库中
            orderService?.saveDataToDataBase(user_id)
            println("""return "ok" to other services""")
        }
    
    }

    因为在Spring Boot中,有需要是自动导入的实例,如果这时候,我们使用?来规避抛出null异常,代码运行的是没有问题的。但是,数据呢?并没有保存到数据库中。

    再次强调,千万不要滥用Kotlin ?的空检查。

  • 相关阅读:
    战火魔兽CJQ圣印问题
    sublime插件总汇
    js引用类型
    一、vue的数据双向绑定的实现
    渲染机制
    帆布指纹识别
    call、apply与bind在理解
    webpack的世界
    line-height与vertical-align
    'abc' 转换成[a, b, c]一道面试题的思考
  • 原文地址:https://www.cnblogs.com/H-BolinBlog/p/9121670.html
Copyright © 2020-2023  润新知