避免空值检查条件运算符样板的最佳实践 [英] Best practice to avoid null-check conditional operator boilerplate

查看:145
本文介绍了避免空值检查条件运算符样板的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当无法使用null对象时,更换条件运算符null-checks样板的最佳做法是:

When it is not possible to use null object, what is the best practice to replace conditional operator null-checks boilerplate like this:

public String getEmployeeName() {
    return employee == null ? null : employee.getName();
}

在Java 8或任何实用程序库中是否有类似下面的内容?

Is there something like below in Java 8 or any utility library?

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(); 是最具可读性的,所以也许它是更好的解决方案,而不仅仅是让你的代码过于复杂。它完成了工作,并没有任何问题 - 所以不妨使用它。这就是条件运算符的用途。

I find return employee == null ? null : employee.getName(); to be the most readable, so perhaps it is the better solution instead of just making your code overly complex. It gets the job done, and there's nothing wrong with it - so might as well use it. That's what the conditional operator is for.

通常在尝试决定使用哪种编程模式时,最好使用最易读且最简单的模式。未来的代码维护者需要了解。

Often when trying to decide which programming pattern to use, it is best to use the pattern that is the most readable and the easiest for future maintainers of your code to understand.

这篇关于避免空值检查条件运算符样板的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆