agurylev
agurylev

Reputation: 381

How to use enrichment (external) call during iterating over streams?

Is it OK to use enrichment (external) API call during iterating over a stream?

For example, the following code snippet:

User[] fullUsers = plainUsers.stream().map(user -> {
        user.setComments(restAPI.getUserComments(user.getId()));
        return user;
    }).toArray();

Here we see a call to some external restAPI system to fill the field in User entity.

Is this approach fine or we should a different approach once dealing with enrichment/external systems?

Upvotes: 0

Views: 274

Answers (1)

John Kugelman
John Kugelman

Reputation: 361710

Streams are a functional idiom, and functional code should strive to be immutable and free of side effects. It's not a good practice to modify stream items. It's technically possible, but I would definitely flag it in a code review.

The purpose of map() is to transform objects into new objects. It's not to modify the existing objects in place. It's a code smell that you're returning the very object that was passed in.

I would recommend using forEach() instead. It's designed to have side effects.

plainUsers.forEach(user -> user.setComments(restAPI.getUserComments(user.getId()));
User[] fullUsers = plainUsers.toArray(new User[0]);

Alternatively, an explicit for loop works just as well:

for (User user: plainUsers) {
    user.setComments(restAPI.getUserComments(user.getId()));
}

User[] fullUsers = plainUsers.toArray(new User[0]);

Upvotes: 3

Related Questions