Search code examples
javareactor

Reactor, best practice to retrieve nested (multiple levels) objects?


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())

Solution

  • 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.