優雅的判空操作 --> 對需要頻繁判空的對象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