3 Immutable values

 

In this chapter you will learn

  • why mutability is dangerous
  • how to fight mutability by working with copies
  • what shared mutable state is
  • how to fight mutability by working with immutable values
  • how to use immutable APIs of String and List

Bad programmers worry about the code. Good programmers worry about data structures and their relationships.

—Linus Torvalds

The fuel for the engine

In the last chapter we met the pure function, which is going to be our best friend throughout the rest of the book. We introduced and briefly discussed some caveats regarding values that may change—mutable states. This chapter focuses on problems with mutable states and explains why pure functions can’t use them in the majority of cases. We are going to learn about immutable values, which are used extensively in functional programming. The relation between a pure function and an immutable value is so strong that we can define functional programming using just two concepts.

Functional programming

is programming using pure functions that manipulate immutable values.

If pure functions make up the engine of functional programs, immutable values are its fuel, oil, and fumes.

Another case for immutability

 
 
 

The European trip

 
 

Can you trust this function?

 
 
 

Mutability is dangerous

 

Functions that lie ... again

 
 

Fighting mutability by working with copies

 
 
 

Mutating values inside the pure function

 
 
 

Coffee break: Getting burned by mutability

 
 
 
 

Lap times

 
 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest