优雅的判空操作 --> 对需要频繁判空的对象entity的代码优化
代码结构
entity是本文用到的对象,里面还用到了entityReturn作为field和getEntityReturn的返回值,如下图红框
Entity对应的接口:entity是Ientity的实现类,Nullentity也是这个接口实现类
相同的,entityReturn也是相似的套路
看红色箭头->
简洁 放心 的 调用 过程 是下面这样的
int code = entityFactory.getEntity().returnEntityMethod().getCode();
对比下面这种
entity entity = entityFactory.getEntity();
if(entity !=null){
//dosomething
entityReturn entityReturn = entity.returnEntityMethod()
if(entityReturn !=null){
int code = entityReturn.getcode();
}else{
//do nothing
}
}else{
//do nothing
}
wiki对这种优化的介绍->https://en.wikipedia.org/wiki/Null_object_pattern#Java