Refactoring for DRY

Brian Goetz brian.goetz at oracle.com
Tue Apr 9 06:19:56 PDT 2013


Richard is absolutely right.  Putting side-effects inside a lambda 
passed to map, flatMap, etc, is a Bad Idea -- regardless of whether you 
can prove that *in this particular case* it might be safe.  Don't code 
like this, and please don't write examples like this in books :)

DRY is a good principle, but that doesn't mean it necessarily trumps all 
other good principles.

On 4/9/2013 6:02 AM, Richard Warburton wrote:
>> But aggressively I might optimize by only doing a single pass:
>>
>>      double sum = people.parallelStream().flatMap( (Person p,
>> Consumer<Person> c) -> {
>>        if (p.getAge() >= 12 && p.getAge() < 65) {
>>          if (p.hasCoupon()) {
>>            p.setPrice(9.25);
>>          } else {
>>            p.setPrice(7.25);
>>          }
>>        } else {
>>          p.setPrice(5.25);
>>        }
>>        p.display();
>>        c.accept(p);
>>      }).map(Person::getPrice)
>>              .collect(Collectors.toDoubleSummaryStatistics(d ->
>> d)).getSum();
>>
>
> Even leaving aside the question of tee()/peek() is this code really a good
> candidate to be run in parallel?
>
> Its pretty unreasonable to expect display to not have side effects, does
> their ordering matter, and the consumer needs to be thread-safe.  Does this
> not get people away from the driving motivation of minimising and
> controlling side effects in order to make safe concurrent code easier to
> write?
>
> I'm really wondering because to my mind this is the kind of code I'd
> recommend people don't write with lambdas.
>
> regards,
>
>    Richard Warburton
>
>    http://insightfullogic.com
>    @RichardWarburto <http://twitter.com/richardwarburto>
>


More information about the lambda-dev mailing list