Java 8 ifPresent vs三元运算符 [英] Java 8 ifPresent vs ternary operator

查看:2008
本文介绍了Java 8 ifPresent vs三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你觉得什么更好(当然有论据):

What do you think is better (with arguments, of course):

Optional.ofNullable( userName )
      .ifPresent( nonNullUserName  -> header.setUser( createUser( nonNullUserName ) ) );

header.setUser( userName == null ? createUser( userName ) : null );

方法 createUser 创建xml元素和整个代码安静的意图是根据 userName 的存在将其设置在SOAP请求中。

The method createUser creates xml element and the intent of the whole peace of code is to set it in a SOAP request depending on presence of userName.

我看到的第一种方法的好处是没有无用的操作,代码做了一件事,没有更多。但是第二种方法可以让你保存一行代码,因此看起来更简洁。

The benefits of the first approach I see is the absence of useless operations, the code does one thing and no more. But the second approach lets you save one more line of code thus appearing to be more laconic.

更新:我想我错过了一件事我实际上暗示了,它引起了一些误解。如果你有一些解释,最好提供更简洁的例子。

UPDATE: I guess I missed a thing I actually implied and it caused certain misunderstanding. It would be better to provide cleaner examples with explanations if you have some.

推荐答案

可选设计用作返回类型对于不能总是返回值的方法,例如 getFirstElementOfAList(),如果列表为空则无法返回任何其他内容:返回null将不太清楚而不是返回一个空的Optional,并且可能意味着第一个元素为null,而不是没有第一个元素。

Optional was designed to be used as a return type for methods that can't always return a value, like for example getFirstElementOfAList(), which can't return anything else if the list is empty: returning null would be less clear than returning an empty Optional, and could mean that the first element is null, and not that there is no first element.

设计者不打算使用Optional作为连锁方法的便利构造。请参阅 Stuart Marks的演示文稿(在JDK上工作),尤其是他所说的内容在第28分钟:

The designers don't intend Optional to be used as a convenience construct to chain methods. See the presentation by Stuart Marks (who works on the JDK), and especially what he says at the 28th minute:


为链接方法的特定目的创建一个Optional通常是一个坏主意[...]

It's generally a bad idea to create an Optional for the specific purpose of chaining methods [...]

您当然可以自由地不尊重预期的设计和最佳做法,但您的同事可能也可以自由地讨厌您: - )

You're of course free to disrespect the intended design and the best practices, but your colleagues might also be free to hate you for that :-)

请注意,您发布的两个片段不会做同样的事情。如果用户名为null,则第一个不执行任何操作,而第二个将用户设置为null(这可能反过来抛出异常或覆盖先前的值)

Note that the two snippets you posted don't do the same thing. The first one does nothing if the user name is null, whereas the second one sets the user to null (which might in turn throw an exception or overwrite the previous value)

我会使用(假设你想要的是第一个版本):

I would just use (assuming what you want is the first version):

if (userName != null) { 
    header.setUser(createUser(userName)); 
}

非常清楚,不滥用可选,并且不会创建一个可选的实例,只是为了链接方法。

which is extremely clear, doesn't abuse Optional, and doesn't create an Optional instance just to chain methods.

这篇关于Java 8 ifPresent vs三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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