Reputation: 210
I am new to reactive programming and i am looking is that a good practice to perform multiple tasks in single map or i should create separate map for each single operation.
Method 1
Mono.just(new Hashmap())
.map(m -> {m.put("One"); return m;})
.map(m -> {m.put("Two"); return m;})
.map(m -> {m.put("Three"); return m;})
Method 2
Mono.just(new Hashmap())
.map(m -> {
m.put("One");
m.put("Two");
m.put("Three");
return m;
})
So which one is best practice is any performance impact specially?
Let me define it more clearly. I would like to know is that a good practice to type more than one purpose code in one map or i should create map for each purpose like i have a User object now i would like to update its ten fields may me twenty.
so if i use single map my code looks like this.
Mono.just(new User())
.map(user -> {
user.setFirstName("abc");
user.setMiddleName("abc");
user.setLastName("abc");
user.setEmail("abc");
user.setAddress("abc");
// setting twenty more fields.
return user;
});
or should i do each assignment in separate map like this
Mono.just(new User())
.map(user-> {user.setFirstName("abc"); return user;})
.map(user-> {user.setMiddleName("abc"); return user;})
.map(user-> {user.setLastName("abc"); return user;})
//twenty more map function called to set each property
which is the best practice?
Upvotes: 3
Views: 1280
Reputation: 72389
So which one is best practice is any performance impact specially?
Performance makes little difference in practice, as reactor has built in fuseable optimisations, meaning your multiple map calls are fused into a single operator in practice.
The focus should, IMHO, therefore be on whichever approach is the clearest to read - and in this case (again, for me at least), it's the approach which simply uses one map call.
The other, bigger recommendation I'd have however is to use immutable objects throughout your chain where possible, rather than mutating objects in a chain directly through map calls. This isn't really what a map call is for, and mutating objects in this way is undesirable for a number of reasons. For POJOs you may want to use something like lombok's @With
instead, eg:
Mono.just(new User())
.map(user ->
user.withFirstName("abc")
.withMiddleName("abc")
.withLastName("abc")
.withEmail("abc")
.withAddress("abc")
);
While in this contrived example it makes no functional difference, it is clearer to read, and is using a map "properly" (to map to a new value rather than mutate an existing one.) In real-world usage it's also much less error prone, and much easier to reason about the state of a reactive chain as a result.
Upvotes: 2