[英]Writing custom Lint rule to ensure null-check before every using to avoid NullPointerException
[英]Best practice to avoid null-check conditional operator boilerplate
当无法使用null对象时,更换条件运算符null-checks样板的最佳做法是:
public String getEmployeeName() {
return employee == null ? null : employee.getName();
}
在Java 8或任何实用程序库中是否有类似下面的内容?
public String getEmployeeName() {
return nullable(employee, employee -> employee.getName());
}
private <T, R> R nullable(T nullable, Function<T, R> doIfNotNull) {
return nullable == null ? null : doIfNotNull.apply(nullable);
}
我发现return employee == null ? null : employee.getName();
return employee == null ? null : employee.getName();
是最可读的,所以也许它是更好的解决方案,而不仅仅是让你的代码过于复杂。 它完成了工作,并没有任何问题 - 所以不妨使用它。 这就是条件运算符的用途。
通常在尝试决定使用哪种编程模式时,最好使用最易读且最容易让代码的维护人员理解的模式。
您可以将代码重构为:
public String getEmployeeName() {
return Optional.ofNullable(employee).map(Employee::getName).orElse(null);
}
ofNullable
从给定的雇员中创建一个Optional
值:如果为null
,则返回空的Optional
; 否则Optional
返回包含雇员。 然后,该Optional
被映射到使用雇员的姓名map
,它返回一个新的Optional
施加给定的映射器,如果Optional
为非空并且一个空Optional
如果Optional
为空。 最后, orElse
返回雇员的名称或null
是Optional
是空的。
话虽如此,我认为将此代码放在null
-check和条件运算符上没有任何附加价值:它可能会有更好的性能,也可能更容易阅读。
Java 8具有新的Optional
类,例如
private Optional<Employee> employee = Optional.empty();
public Optional<Employee> getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = Optional.of(employee); // null not allowed
}
public void removeEmployee() {
this.employee = Optional.empty();
}
employee
永远不会为null
,但可能是“空的”。
然后可以通过两种方式实现getEmployeeName()
方法:
// Returning Optional (never null)
public Optional<String> getEmployeeName() {
return this.employee.map(Employee::getName);
}
// Standard getter (may return null)
public String getEmployeeName() {
return this.employee.map(Employee::getName).orElse(null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.