Java 什么';最佳做法是什么?
在java中执行此检查的最佳方法是什么Java 什么';最佳做法是什么?,java,Java,在java中执行此检查的最佳方法是什么 BigDecimal valorAtualizado = dotacaoPersist.buscarValorAtualizadoGastoComPessoal(codAdm, anoRef, codFunc); if(valorAtualizado != null){ return valorAtualizado; } return BigDecimal.ZE
BigDecimal valorAtualizado = dotacaoPersist.buscarValorAtualizadoGastoComPessoal(codAdm, anoRef, codFunc);
if(valorAtualizado != null){
return valorAtualizado;
}
return BigDecimal.ZERO;
或
两个版本都相当于这一行
return whatever.do();
你可以用这个-
return (null!=a ? a : null);
但是从调用方法返回null不是一个好主意。相反,您可以返回一些伪值。例如,您试图从getStudents()
方法获取studentList
。然后,您可以返回空的学生列表,而不是返回一个null
public List<Student> getStudents(){
List<Student> studentList = someMethodReturnsStudentList();
return (null!=studentList ? studentList : Collections.EMPTY_LIST);
}
public List getStudents(){
List studentList=someMethodReturnsStudentList();
return(null!=studentList?studentList:Collections.EMPTY\u LIST);
}
使用此技术的好处是使用getStudent()
的客户端方法不需要进一步考虑空检查
希望它能有所帮助。
返回任何内容。do()代码>?如果我没弄错的话,它们在汇编级别看起来都是一样的……两种解决方案几乎是一样的。另外,你可以最小化代码在理解方面,我更喜欢第二个。更容易理解逻辑。但是这个问题是关于,哪一个是最好的实践还是哪一个有最好的性能?Evgeniy Dorofev你是对的,两个版本都是等效的,所以不要像你的答案那样使用它们
public List<Student> getStudents(){
List<Student> studentList = someMethodReturnsStudentList();
return (null!=studentList ? studentList : Collections.EMPTY_LIST);
}