反应堆,检索嵌套(多个级别)对象的最佳实践?

发布于 2025-01-18 21:41:25 字数 533 浏览 3 评论 0原文

假设以下对象:

public class Employee {

    private Address address;
public class Address {

    private String street;
    private String country;

以下两个过程中哪一个是“最佳”(最佳实践和/或性能)?

答:

return Mono.just(employee)
            .map(employee -> employee.getAddress().getCountry())

乙:

return Mono.just(employee)
            .map(employee -> employee.getAddress())
            .map(address -> address.getCountry())

Suppose the following objects :

public class Employee {

    private Address address;
public class Address {

    private String street;
    private String country;

Which of the two following processes is the "best" (best practice and/or performance) ?

A :

return Mono.just(employee)
            .map(employee -> employee.getAddress().getCountry())

B :

return Mono.just(employee)
            .map(employee -> employee.getAddress())
            .map(address -> address.getCountry())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸩远一方 2025-01-25 21:41:25

第二种方法更可取:

return Mono.just(employee)
            .map(employee -> employee.getAddress())
            .map(address -> address.getCountry())

因为您可以通过为每个 getter 添加单独的函数或使用方法引用来使其更简单:

return Mono.just(employee).map(Emploee::getAddress).map(Address::getCountry)

这是明显的示例,但在更复杂的情况下,通过使用方法引用来简化代码可能会很重要。
此外,方法链接employee.getAddress().getCountry()并不是一个好的实践。您可以在那里阅读有关方法链讨论的更多信息

The second approach is more preferable:

return Mono.just(employee)
            .map(employee -> employee.getAddress())
            .map(address -> address.getCountry())

because you can make it simpler by adding a separete functions for each getter, or using method reference:

return Mono.just(employee).map(Emploee::getAddress).map(Address::getCountry)

It's obvious example, but in more complicated cases simplification of code by using method refecences could be significant.
Moreover, method chaining employee.getAddress().getCountry() isn't a good practice. You can read more about method chaining discussion there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文