Refactoring for DRY

Sam Pullara spullara at gmail.com
Mon Apr 8 19:30:50 PDT 2013


So as a first pass, I would do normal refactoring to use the API more effectively:

    Predicate<Person> ageRange = p -> p.getAge() >= 12 && p.getAge() < 65;

    people.parallelStream()
            .filter(ageRange)
            .forEach(p -> {
              p.setPrice(9.25);
            });

    people.parallelStream()
            .filter(ageRange.and(Person::hasCoupon))
            .forEach(p -> {
              p.setPrice(p.getPrice() - 2.00);
            });

    people.parallelStream()
            .filter(ageRange.negate())
            .forEach(p -> {
              p.setPrice(5.25);
            });

    people.stream()
            .forEach(p -> {
              p.display();
            });

    double sum = people.stream().map(p -> p.getPrice()).collect(Collectors.toDoubleSummaryStatistics(d -> d)).getSum();

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();



But that doesn't really address the larger issue of the multiple passes. I think this would be most effectively done with tee()
On Apr 8, 2013, at 4:35 PM, "Barry Burd" <bburd at drew.edu> wrote:

> The following code seems very repetitious to me. Ss there a recommended way to refactor this code?
> 
>    people.parallelStream()
>      .filter(p -> p.getAge() >= 12)
>      .filter(p -> p.getAge() < 65)
>      .forEach(p -> {
>        p.setPrice(9.25);
>      });
> 
>    people.parallelStream()
>      .filter(p -> p.getAge() >= 12)
>      .filter(p -> p.getAge() < 65)
>      .filter(p -> p.hasCoupon())
>      .forEach(p -> {
>        p.setPrice(p.getPrice() - 2.00);
>      });
> 
>    people.parallelStream()
>      .filter(p -> (p.getAge() < 12 || p.getAge() >= 65))
>      .forEach(p -> {
>        p.setPrice(5.25);
>      });
> 
>    people.stream()
>      .forEach(p -> {
>        p.display();
>      });
> 
>    people.stream().map(p -> p.getPrice()).forEach(amount -> total += amount);
> 



More information about the lambda-dev mailing list