当我在适配器中绑定(bind)数据时,我使用模型来执行此操作。
class ModelA{
ModelB b;
......
geters and setters
}
class ModelB{
ModelC c;
......
geters and setters
}
class ModelC{
String name;
......
geters and setters
}
当我想使用名字时,我需要这样做:
bindData(ModelA a) {
String name = a.getModelB().getModelC().getName();
mTextView.setText(name);
}
但是模型可能为空,所以我添加了这个:
bindData(ModelA a) {
if(a != null && a.getModelB() != null
&& a.getModelC() != null
&&!TextUtils.isempty(a.getModelB().getModelC().getName())) {
String name = a.getModelB().getModelC().getName();
mTextView.setText(name);
}
}
但是我认为使用 try catch 可能更容易,所以我改变了这个:
bindData(ModelA a) {
try{
String name = a.getModelB().getModelC().getName();
mTextView.setText(name);
}catch (NullPointerException e) {
......
}
}
有没有更好的方法来判断model是否为null?如果不是,“if”和“try catch”哪个更好?
最佳答案
在我的例子中,我提前检查了模型是否为 null,并且我没有检查 getter() 中的变量。因为如果它为 null,我们就不需要渲染 View 。 (这是我想将 Java 迁移到 Kotlin 的原因之一,因为我不喜欢检查 NULL)
initViews() {
// handle your default data for Views
}
renderViews(ModelA a) {
ModelB modelB = a.getModelB;
if (modelB == null {
return;
}
// bind data of ModelB to Views
ModelC modelC = modelB.getModelC();
if (modelC == null) {
return;
}
// bind data of ModelC to Views
String name = modelC.getName();
mTextView.setText(name);
}
关于android - 判断模型是否为空的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47745438/