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 代码 - 云+社区 - 腾讯云】
如有不对,敬请指出,谢谢。