2 Pure Functions

 

In this chapter you will learn

  • why do we need pure functions?
  • how to pass copies of the data
  • how to recalculate instead of storing
  • how to pass the state
  • how to test pure functions

Sometimes, the elegant implementation is just a function.

Not a method. Not a class. Not a framework.

Just a function.

— John Carmack

2.1 Why do we need pure functions?

In the last chapter we learned about functions that don’t lie. Their signatures tell the whole story about their body. We concluded that these are the functions we can trust: fewer surprises when we code, the fewer bugs in the applications we create. In this chapter we will learn about the most trustworthy of all the functions that don’t lie: a pure function.

THIS IS BIG!

pure functions are the foundation of functional programming

Shopping cart discounts

Let’s start by looking at an example that doesn’t use pure functions. We’ll go through its problems and try to solve them intuitively first. Our task is to write a “shopping cart functionality” that is able to calculate discounts based on the current cart contents. Namely:

2.2 Coding imperatively

2.3 Breaking the code

2.4 Passing copies of the data

2.5 Breaking the code... again

2.6 Recalculating instead of storing

2.7 Focusing on the logic by passing the state

2.8 Where did the state go?

2.9 Difference between impure & pure functions

2.10 Coffee Break: Refactoring to a pure function

2.11 Coffee Break Explained: Refactoring to a pure function

2.12 In pure functions we trust

2.13 Pure functions in programming languages

2.14 Difficulty of staying pure...

2.15 Pure functions and clean code

2.16 Coffee Break: Pure or impure?

2.17 Coffee Break Explained: Pure or impure?

2.18 Using Scala to write pure functions

2.19 Practicing pure functions in Scala

2.20 Testing pure functions

2.21 Coffee Break: Testing pure functions

2.22 Coffee Break Explained: Testing pure functions

2.23 Summary