#Is this anti pattern ?
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
its worse, its a bug
peek must NOT be used for logic
peek can be skipped for example
read its javadoc to be sure what it is and what it can be used for
apart from that im not sure what ur curious about specifically in that code snippet
example, sth like persons.peek(...).count() will not run peek on any element
as count can be answered without looking up any element (in many cases), so its skipped
use map if u want to run sth on all elements
Well in my case
toList() - all elements are guaranteed to be processed
enrichDto - mutates the DTO in-place
I believe it's safe in my situation
even if u dont want to change the stream, then do map(x -> { foo(x); return x; })
u can also make urself a helper for that
I am not sure if toList even guarantees that
for example if the underlying stream datasource is a list already
point is, if its not promised in the javadoc and u rely on it... ur in for a surprise eventually
maybe it works in the current implementation but then 3 years later it might be changed and ur code is wrong
Thats actually true
and what does "enrichDto" even do, sounds more like you want to use map
the idiomatic name for this btw is accept. also is also common
persons.accept(...)
u could make urself a helper like Streams.accept(..) so u can static-import it and write persons.map(accept(...))
but yeah
or u just write it out .map(x -> {...; return x;})
So now its kinda like
return enrichDto(funnyService.findByExternal(externalId).orElseThrow());
return funnyService.findAll(limit).stream().map(this::enrichDto).toList();
and enrichDto returns the funnyDto
I hope i didnt mix the naming now haha
Thanks guys
still bad
you want to replace enrichDTO by a pure function that transform an object into another, instead of mutating it
streams aren't made for mutating objects at the first place
If at the creation of your object, the object state is not already correct and full, your code is flawed.
Which is not to say that mutable objects are bad (even if not encouraged), just that the object should always be in a valid state.
This should also apply to transitional states - though established patterns in many frameworks frequently violates that (eg co-dependent properties being set one at a time on an entity).