Refactoring for DRY (original) (raw)
Brian Goetz brian.goetz at oracle.com
Tue Apr 9 14:01:22 PDT 2013
- Previous message: Refactoring for DRY
- Next message: Refactoring for DRY
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
The recommendation is to format chains like:
sales.stream() .map(...) .reduce(...)
so that it is very obvious what steps are being performed on the data. This allows users to very quickly figure out the structure of the pipeline, and if they're interested, the can scan farther right to see exactly what transformations are being applied.
For your reduce stage, I would replace the lambda you've got with
.reduce(Double::sum)
since again this is far more readable. Or even better:
.mapToInt(Sale::getPrice)
.sum();
On 4/9/2013 4:55 PM, Barry Burd wrote:
How's this version (of a simple example to introduce some of the functional programming concepts)? Note: I'm not using type inference because my readers are better off learning about that later. Also, I'm using System.out.println in order to have a complete, self-contained example, but I'm saving that System.out.println call to the very end to avoid mixing side-effects with the functional code.
import java.text.NumberFormat; import java.util.ArrayList; public class TallySales { ArrayList sales = new ArrayList(); NumberFormat currency = NumberFormat .getCurrencyInstance(); public static void main(String[] args) { new TallySales(); } TallySales() { fillArray(sales); System.out.println(currency.format(sales.stream().map((Sale sale) -> sale.getPrice()).reduce((Double price1, Double price2) -> price1 + price2).get())); } private void fillArray(ArrayList sales) { sales.add(new Sale("DVD", 15.00, true)); sales.add(new Sale("Book", 12.00, false)); sales.add(new Sale("DVD", 21.00, true)); sales.add(new Sale("Magazine", 5.25, true)); } }
- Previous message: Refactoring for DRY
- Next message: Refactoring for DRY
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]