Can anyone explain me what is state and mutable data?
State refers collectively to the data stored in the object that determines the current properties of the object. For example, if you have a BankAccount
object, the owner of the account and the amount of money in it represent the state of the account.
However, not all state is bad for functional programming, only the mutable+ one is not acceptable. For example, the characters of which a string is composed is that string's state. If you cannot change the content of the string, it is said to have an immutable state. This fits well with functional programming paradigm.
+ mutable is a fancy word for "changeable".
mutable suggest anything that can change, i.e. an int
int a = 0;
System.out.prtinln(a); //prints 0
a = 2;
System.out.prtinln(a); //now prints 2, so its mutable
In java a string is immutable. you cannot change the string value only its reference.
String s1 = "Hello";
System.out.println(s1); //prints Hello
String s2 = s1;
s1 = "Hi";
System.out.println(s2); //prints "Hello" and not "Hi"
State is something which an instance of a class will have (an Object).
If an Object has certain values for its attributes its in a diffrent state then another Object of the same class with diffrent attribute values
Mutable state is everything that can make a function return a different value, despite it being called with the same arguments.
Simple example in Java:
public static double badSqrt(double x) {
double r = Math.sqrt(x);
if (System.currentTimeMillis() % 42L == 0L) return r;
return r + 0.000000001;
}
This function computes a slightly incorrect result sometimes. We say that badSqrt
is impure, because its result does not solely depend on its argument (and constants).
For the person debugging a program that contains calls to badSqrt() or impure functions in general this is a nightmare. Often, the program seems to work, but once in a while, wrong results are delivered. Unless the function is clearly documented or the source code is available, it'll be hard to track the bug.
In such cases, it is said that the behaviour of the functions depends on mutable state. This is state that could be changed (mutated) by completely unrelated parts of the program, or, like in the example, by another program (the operating system).