The Big Gains of Functional-Style Code

Functional-style code has a higher signal-to-noise ratio; we write fewer lines of code, but each line or expression achieves more. We gained quite a bit from the functional-style version, compared with the imperative-style version:

  • We avoided explicit mutation or reassignment of variables, which are often sources of bugs and result in code that’s hard to make concurrent. In the imperative version we repeatedly set the totalOfDiscountedPrices variable within the loop. In the functional-style version, there is no explicit mutation in our code. Fewer mutations leads to fewer errors in code.

  • The functional version can easily be parallelized. If the computation was time consuming, we can easily run it concurrently ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.