Is it common to have code that looks "imperative" supporting reactive code?

SoCal :

It seems like I'm starting to write "imperative looking" methods to support the functionality/readability of the reactive chains. This may not be the most technical of questions, but is this common?

@Component
public class MyRequestHandler {

    public Mono<ServerResponse> add(ServerRequest request) {
        return request.bodyToMono(MyPOJO.class).flatMap(this::add)
                                                 .switchIfEmpty(ServerResponse.noContent().build());
    }

    /*
     * this code supports add(ServerRequest)
     *   also simplifies returning a Mono<ServerResponse>
     */
    private Mono<ServerResponse> add(MyPOJO myPOJO) {
        System.out.println("Received >> " + myPOJO.toString());
        return (myPOJO.getValue() % 2 == 0 ) ? ServerResponse.ok()
                                                               .body(Mono.just(true), Boolean.class)
                                               : ServerResponse.ok()
                                                               .body(Mono.just(false), Boolean.class);
    }
}
Michael Berry :

Mixing imperative code and reactive / functional code is sometimes the clearest way of doing things - there's nothing inherently wrong with it. (Sometimes it's done because the author doesn't know of the "better" functional way, but so long as it's readable there's nothing inherently wrong with that either.)

However, there's nothing particularly "imperative" about your code here - you've just extracted the inner flatMap() code into a separate method. That method is still returning a reactive element, and consists of a single reactive streams call.

Is this normal, and is it accepted? Yes to both. Same rules apply here as with "normal" OO programming, that being to separate your code out into testable, reusable (or potentially reusable) elements.

There's just two additional points I'd note here. Firstly, there's no need for the ternary operator at all in your example, better would be:

return ServerResponse.ok()
        .body(Mono.just(myPOJO.getValue() % 2 == 0), Boolean.class)

Secondly, instead of arbitrarily printing out "received" values in a hook for debugging purposes, you can use log() on your Flux and use the "TRACE" debug level to give you much more detailed logging.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=146660&siteId=1
Recommended