4 Functions as values

 

In this chapter you will learn

  • how to pass functions as arguments
  • how to use the sortBy function
  • how to use map and filter functions
  • how to return functions from functions
  • how to treat functions as values
  • how to use the foldLeft function
  • how to model immutable data using product types

The most damaging phrase in the language is: ‘We’ve always done it this way!’

—Grace Hopper

Implementing requirements as functions

We spent some time working with pure functions and immutable values. They make up the foundation of functional programming. This chapter focuses on showing how well these two concepts work together. We will discover how helpful it is to think about business requirements in terms of functions and how to treat pure functions as values.

Ranking words

We need to implement a functionality that ranks words in some word-based puzzle game.

Warning

Initial requirements may seem trivial, but be warned that we will be changing them and adding new requirements. This will allow us to check how well our code is prepared for such changes.

Impure functions and mutable values strike back

Version #1: Using Comparator and sort

Using Java Streams to sort the list

Version #2: Ranking the words using Streams

Function signatures should tell the whole story

Version #3: Passing algorithms as arguments

Changing requirements