Android业务开发中assert的使用

1. assert(boolean)

        官方解释是:Throws an AssertionError if the value is false and runtime assertions have been enabled on the JVM using the -ea JVM option.

        简单理解是:用来检测执行结果,当boolean为false时,抛出AssertionError,但是需要在开启对应的JVM选项(-ea)时才生效。

2. 使用assert的好处

        减少在编码的时候,做的很多ifelse检测判断,以及减少代码层级。比如:某个变量是否为null,某个成员属性是否为true等。

3. assert代码使用

    override fun convert(helper: BaseViewHolder, item: MultiItemEntity?) {
        assert(item is WrapperMultiItemEntity)
        val data = item as WrapperMultiItemEntity
        assert(data.data != null)

        when (helper.itemViewType) {
            MAP.value -> convertExperience(helper, data.data as RecommendInfo)
        }
    }

4. assert思考

        之前我们一般是在写单测时才使用到assert,那么在业务代码中使用它是否会产生副作用呢?下面看看反编译后代码:

4.1 Objects.requireNonNull 

Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:
       public Foo(Bar bar, Baz baz) {
           this.bar = Objects.requireNonNull(bar, "bar must not be null");
           this.baz = Objects.requireNonNull(baz, "baz must not be null");
       }
       
Params:
    obj – the object reference to check for nullity message – detail message to be used in the event that a NullPointerException is thrown
Type parameters:    <T> – the type of the reference
Returns:    obj if not null
Throws:    NullPointerException – if obj is null

    public static <T> T requireNonNull(T obj, String message) {
        if (obj == null)
            throw new NullPointerException(message);
        return obj;
    }

4.2 release版本与debug版本的差异

        可以看到,断言为false时,debug版本会抛出AssertionError,且当数据异常时,会抛出new NullPointerException异常。

        而对于release版本,并未抛出AssertionError,也就是说并为对assert语句进行断言,当数据异常时,相应的使用Objects.requireNonNull代替new NullPointerException去抛出异常,所以如果数据存在异常,还是会抛出的。

        对于debug和release版本的代码不一致,应该是因为release打包时并未开启JVM的-es(ps:根据调试现象和反编译代码猜测如此,不一定准确)

 5.0 小结

        综上所述,业务代码中可以使用assert进行编码,以减少ifelse的判断和代码层级。

附:参考【用好 Require,check,assert,写好 Kotlin 代码 - 云+社区 - 腾讯云

如有不对,敬请指出,谢谢。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值