zoukankan      html  css  js  c++  java
  • 请不要乱用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 ?的空检查。

  • 相关阅读:
    电梯调度算法---结对项目小进展
    程序的单元测试—软件工程课上所获得的感悟
    软件工程之个人项目--词频统计
    c语言中文件的读写函数
    9、访问或添加属性
    5、AOP例子(切面,通知,切入点)
    6、AOP相关概念
    4、SSH集成笔记
    3、整合SSH遇到的问题
    1、各个包的作用
  • 原文地址:https://www.cnblogs.com/H-BolinBlog/p/9121670.html
Copyright © 2011-2022 走看看