BobLoblaw
BobLoblaw

Reputation: 2001

Why do immutable objects enable functional programming?

I'm trying to learn scala and I'm unable to grasp this concept. Why does making an object immutable help prevent side-effects in functions. Can anyone explain like I'm five?

Upvotes: 46

Views: 13377

Answers (8)

aderchox
aderchox

Reputation: 4074

I've read all the answers and they don't satisfy me, because they mostly talk about "immutability", and not about its relation to FP.

The main question is:

Why do immutable objects enable functional programming?

So I've searched a bit more and I have another answer, I believe the easy answer to this question is: "Because Functional Programming is basically defined on the basis of functions that are easy to reason about". Here's the definition of Functional Programming:

The process of building software by composing pure functions.

If a function is not pure -- which means receiving the same input, it's not guaranteed to always produce the same output (e.g., if the function relies on a global object, or date and time, or a random number to compute the output) -- then that function is unpredictable, that's it! Now exactly the same story goes about "immutability" as well, if objects are not immutable, a function with the same object as its input may have different results (aka side effects) each time used, and this will make it hard to reason about the program.

I first tried to put this in a comment, but it got longer than the limit, I'm by no means a pro so please take this answer with a grain of salt.

Upvotes: 0

Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

Why do immutable objects enable functional programming?

They don't.

Take one definition of "function," or "prodecure," "routine" or "method," which I believe applies to many programming languages: "A section of code, typically named, accepting arguments and/or returning a value."

Take one definition of "functional programming:" "Programming using functions." The ability to program with functions is indepedent of whether state is modified.

For instance, Scheme is considered a functional programming language. It features tail calls, higher-order functions and aggregate operations using functions. It also has mutable objects. While mutability destroys some nice mathematical qualities, it does not necessarily prevent "functional programming."

Upvotes: 1

Jens Schauder
Jens Schauder

Reputation: 81907

One important property of functional programming is: If I call the same function twice with the same arguments I'll get the same result. This makes reasoning about code much easier in many cases.

Now imagine a function returning the attribute content of some object. If that content can change the function might return different results on different calls with the same argument. => no more functional programming.

Upvotes: 5

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297195

Interesting question, a bit difficult to answer.

Functional programming is very much about using mathematics to reason about programs. To do so, one needs a formalism that describe the programs and how one can make proofs about properties they might have.

There are many models of computation that provide such formalisms, such as lambda calculus and turing machines. And there's a certain degree of equivalency between them (see this question, for a discussion).

In a very real sense, programs with mutability and some other side effects have a direct mapping to functional program. Consider this example:

a = 0
b = 1
a = a + b

Here are two ways of mapping it to functional program. First one, a and b are part of a "state", and each line is a function from a state into a new state:

state1 = (a = 0, b = ?)
state2 = (a = state1.a, b = 1)
state3 = (a = state2.a + state2.b, b = state2.b)

Here's another, where each variable is associated with a time:

(a, t0) = 0
(b, t1) = 1
(a, t2) = (a, t0) + (b, t1)

So, given the above, why not use mutability?

Well, here's the interesting thing about math: the less powerful the formalism is, the easier it is to make proofs with it. Or, to put it in other words, it's too hard to reason about programs that have mutability.

As a consequence, there's very little advance regarding concepts in programming with mutability. The famous Design Patterns were not arrived at through study, nor do they have any mathematical backing. Instead, they are the result of years and years of trial and error, and some of them have since proved to be misguided. Who knows about the other dozens "design patterns" seen everywhere?

Meanwhile, Haskell programmers came up with Functors, Monads, Co-monads, Zippers, Applicatives, Lenses... dozens of concepts with mathematical backing and, most importantly, actual patterns of how code is composed to make up programs. Things you can use to reason about your program, increase reusability and improve correctness. Take a look at the Typeclassopedia for examples.

It's no wonder people not familiar with functional programming get a bit scared with this stuff... by comparison, the rest of the programming world is still working with a few decades-old concepts. The very idea of new concepts is alien.

Unfortunately, all these patterns, all these concepts, only apply with the code they are working with does not contain mutability (or other side effects). If it does, then their properties cease to be valid, and you can't rely on them. You are back to guessing, testing and debugging.

Upvotes: 43

Nate C-K
Nate C-K

Reputation: 5932

In short, if a function mutates an object then it has side effects. Mutation is a side effect. This is just true by definition.

In truth, in a purely functional language it should not matter if an object is technically mutable or immutable, because the language will never "try" to mutate an object anyway. A pure functional language doesn't give you any way to perform side effects.

Scala is not a pure functional language, though, and it runs in the Java environment in which side effects are very popular. In this environment, using objects that are incapable of mutation encourages you to use a pure functional style because it makes a side-effect oriented style impossible. You are using data types to enforce purity because the language does not do it for you.

Now I will say a bunch of other stuff in the hope that it helps this make sense to you.

Fundamental to the concept of a variable in functional languages is referential transparency.

Referential transparency means that there is no difference between a value, and a reference to that value. In a language where this is true, it makes it much simpler to think about a program works, since you never have to stop and ask, is this a value, or a reference to a value? Anyone who's ever programmed in C recognizes that a great part of the challenge of learning that paradigm is knowing which is which at all times.

In order to have referential transparency, the value that a reference refers to can never change.

(Warning, I'm about to make an analogy.)

Think of it this way: in your cell phone, you have saved some phone numbers of other people's cell phones. You assume that whenever you call that phone number, you will reach the person you intend to talk to. If someone else wants to talk to your friend, you give them the phone number and they reach that same person.

If someone changes their cell phone number, this system breaks down. Suddenly, you need to get their new phone number if you want to reach them. Maybe you call the same number six months later and reach a different person. Calling the same number and reaching a different person is what happens when functions perform side effects: you have what seems to be the same thing, but you try to use it, it turns out it's different now. Even if you expected this, what about all the people you gave that number to, are you going to call them all up and tell them that the old number doesn't reach the same person anymore?

You counted on the phone number corresponding to that person, but it didn't really. The phone number system lacks referential transparency: the number isn't really ALWAYS the same as the person.

Functional languages avoid this problem. You can give out your phone number and people will always be able to reach you, for the rest of your life, and will never reach anybody else at that number.

However, in the Java platform, things can change. What you thought was one thing, might turn into another thing a minute later. If this is the case, how can you stop it?

Scala uses the power of types to prevent this, by making classes that have referential transparency. So, even though the language as a whole isn't referentially transparent, your code will be referentially transparent as long as you use immutable types.

Practically speaking, the advantages of coding with immutable types are:

  1. Your code is simpler to read when the reader doesn't have to look out for surprising side effects.
  2. If you use multiple threads, you don't have to worry about locking because shared objects can never change. When you have side effects, you have to really think through the code and figure out all the places where two threads might try to change the same object at the same time, and protect against the problems that this might cause.
  3. Theoretically, at least, the compiler can optimize some code better if it uses only immutable types. I don't know if Java can do this effectively, though, since it allows side effects. This is a toss-up at best, anyway, because there are some problems that can be solved much more efficiently by using side effects.

Upvotes: 26

Kyle
Kyle

Reputation: 22258

I'm running with this 5 year old explanation:

class Account(var myMoney:List[Int] = List(10, 10, 1, 1, 1, 5)) {
  def getBalance = println(myMoney.sum + " dollars available")
  def myMoneyWithInterest = {
    myMoney = myMoney.map(_ * 2)
    println(myMoney.sum + " dollars will accru in 1 year")
  }
}

Assume we are at an ATM and it is using this code to give us account information.

You do the following:

scala> val myAccount = new Account()
myAccount: Account = Account@7f4a6c40

scala> myAccount.getBalance
28 dollars available

scala> myAccount.myMoneyWithInterest
56 dollars will accru in 1 year

scala> myAccount.getBalance
56 dollars available

We mutated the account balance when we wanted to check our current balance plus a years worth of interest. Now we have an incorrect account balance. Bad news for the bank!

If we were using val instead of var to keep track of myMoney in the class definition, we would not have been able to mutate the dollars and raise our balance.

When defining the class (in the REPL) with val:

error: reassignment to val
             myMoney = myMoney.map(_ * 2

Scala is telling us that we wanted an immutable value but are trying to change it!

Thanks to Scala, we can switch to val, re-write our myMoneyWithInterest method and rest assured that our Account class will never alter the balance.

Upvotes: 7

Brian Hsu
Brian Hsu

Reputation: 8821

Nate's answer is great, and here is some example.

In functional programming, there is an important feature that when you call a function with same argument, you always get same return value.

This is always true for immutable objects, because you can't modify them after create it:

class MyValue(val value: Int)

def plus(x: MyValue) = x.value + 10

val x = new MyValue(10)
val y = plus(x) // y is 20
val z = plus(x) // z is still 20, plus(x) will always yield 20

But if you have mutable objects, you can't guarantee that plus(x) will always return same value for same instance of MyValue.

class MyValue(var value: Int)

def plus(x: MyValue) = x.value + 10

val x = new MyValue(10)
val y = plus(x) // y is 20
x.value = 30
val z = plus(x) // z is 40, you can't for sure what value will plus(x) return because MyValue.value may be changed at any point.

Upvotes: 1

JimN
JimN

Reputation: 3150

First a few definitions:

  • A side effect is a change in state -- also called a mutation.
  • An immutable object is an object which does not support mutation, (side effects).

A function which is passed mutable objects (either as parameters or in the global environment) may or may not produce side effects. This is up to the implementation.

However, it is impossible for a function which is passed only immutable objects (either as parameters or in the global environment) to produce side effects. Therefore, exclusive use of immutable objects will preclude the possibility of side effects.

Upvotes: 4

Related Questions