43

This is a newbie question, but I couldn't find a newbie-proof enough answer on Google.

What do people mean when they say 'state' - in programming in general, and in OO programming specifically?

Also, what is mutable and immutable state - again, generally in programming and also specifically in OOP?

0

4 Answers 4

54

You have state when you associate values (numbers, strings, complex data structures) to an identity and a point in time.

For example, the number 10 by itself does not represent any state: it is just a well-defined number and will always be itself: the natural number 10. As another example, the string "HELLO" is a sequence of five characters, and it is completely described by the characters it contains and the sequence in which they appear. In five million years from now, the string "HELLO" will still be the string "HELLO": a pure value.

In order to have state you have to consider a world in which these pure values are associated to some kind of entities that possess an identity. Identity is a primitive idea: it means you can distinguish two things regardless of any other properties they may have. For example, two cars of the same model, same colour, ... are two different cars.

Given these things with identity, you can attach properties to them, described by pure values. E.g., my car has the property of being blue. You can describe this fact by associating the pair

("colour", "blue")

to my car. The pair ("colour", "blue") is a pure value describing the state of that particular car.

State is not only associated to a particular entity, but also to a particular point in time. So, you can say that today, my car has state

("colour", "blue")

Tomorrow I will have it repainted in black and the new state will be

("colour", "black")

Note that the state of an entity can change, but its identity does not change by definition. Well, as long as the entity exists, of course: a car may be created and destroyed, but it will keep its identity throughout its lifetime. It does not make sense to speak about the identity of something that does not exist yet / any more.

If the values of the properties attached to a given entity change over time, you say that the state of that entity is mutable. Otherwise, you say that the state is immutable.

The most common implementation is to store the state of an entity in some kind of variables (global variables, object member variables), i.e. to store the current snapshot of a state. Mutable state is then implemented using assignment: each assignment operation replaces the previous snapshot with a new one. This solution normally uses memory locations to store the current snapshot. Overwriting a memory location is a destructive operation that replaces a snapshot with a new one. (Here you can find an interesting talk about this place-oriented programming approach.)

An alternative is to view the subsequent states (history) of an entity as a stream (possibly infinite sequence) of values, see e.g. Chapter 3 of SICP. In this case, each snapshot is stored at a different memory location, and the program can examine different snapshots at the same time. Unused snapshots can be garbage-collected when they are no longer needed.

Advantages / disadvantages of the two approaches

  • Approach 1 consumes less memory and allows to construct a new snapshot more efficiently since it involves no copying.
  • Approach 1 implicitly pushes the new state to all the parts of a program holding a reference to it, approach 2 would need some mechanism to push a snapshot to its observers, e.g. in the form of an event.
  • Approach 2 can help to prevent inconsistent state errors (e.g. partial state updates): by defining an explicit function that produces a new state from an old one it is easier to distinguish between snapshots produced at different points in time.
  • Approach 2 is more modular in that it allows to easily produce views on the state that are independent of the state itself, e.g. using higher-order functions such as map and filter.
4
  • 1
    Note that objects aren't the only things with state. If a program uses (mutable) global variables, the program itself is said to have state. Likewise, if a function has a variable that remembers values across function calls, the function is stateful.
    – Doval
    Apr 10, 2014 at 18:56
  • 2
    @Doval: You can think of global state as the state of a global world object. As far as I know, this view is used e.g. in Ruby. A function that remembers state is isomorphic to an object with just one method. The common basic idea is that you associate values to identities, or places, i.e. that certain things can hold values (possibly mutable value) but retain their identity.
    – Giorgio
    Apr 10, 2014 at 19:09
  • 3
    Sure, I agree in principle. I'm just making sure Prog understands that statefulness isn't something exclusive to OOP. I don't think the "everything is an object" line of thought comes naturally.
    – Doval
    Apr 10, 2014 at 19:24
  • @Doval: You mentioned stateful functions that remember values across different calls. One example I can think of are static local variables in C. Another example is closures (functions that capture variables defined in their context). Closures are somewhat dual to objects: a closure is an object with exactly one method, whereas an object is a collection of closures defined over the same variables. You probably know all this but I wanted to summarize it here. In general, you can store state in some memory location and access it using different mechanisms, as you pointed out.
    – Giorgio
    Aug 14, 2015 at 19:11
17

State is simply information about something held in memory.

As a simple exercise in object orientation, think of a class as a cookie cutter, and cookies as objects. You can create a cookie (instantiate an object) using the cookie cutter (class). Let's say one of the properties of the cookie is its color (which can be changed by using food coloring). The color of that cookie is part of its state, as are the other properties.

Mutable state is state that can be changed after you make the object (cookie). Immutable state is state that cannot be changed.

Immutable objects (for which none of the state can be changed) become important when you are dealing with concurrency, the ability for more than one processor in your computer to operate on that object at the same time. Immutability guarantees that you can rely on the state to be stable and valid for the object's lifetime.

In general, the state of an object is held in "private or member variables," and accessed through "properties" or getter/setter methods.

6
  • 4
    For the benefit of Prog, the fact that a value never changes is also important because it's much easier to reason about. It can be used in as many functions/methods as you want and you know they can't change it. With mutable state you have to track the history of how that object's been used to figure out what its value has now. That's needless mental overhead if making it immutable doesn't complicate the program.
    – Doval
    Apr 10, 2014 at 17:31
  • Thanks for answering. So basically, in OOP, when someone says 'state', they usually mean "an object's member variables"? If so, then 'mutable state' is public variables, or more common in OOP, private variables that can be changed through setter methods - while 'immutable state' is simply private member variables?
    – Aviv Cohn
    Apr 10, 2014 at 22:29
  • 1
    Immutability can be simulated by simply never writing to an object's private members once they are populated with initial values. Immutability can be enforced using a number of methods: not providing a setter method, requiring the initial value to be set using a constructor parameter, writing in a functional style, using constants, etc. Apr 10, 2014 at 22:38
  • 1
    I think of state as the value of some property of some entity. "Shipped" is a state. So is "Tax Rate." The weight of something is a state. Whether you are currently awake or asleep is a state. The color of something is a state. Meaningful information about something, held in some kind of computer memory. Apr 11, 2014 at 0:16
  • 1
    In many languages, immutability can be enforced by declaring member variables as "const" or "final". Such variables can only be initialised by the constructor. Don't assume that private variables are immutable - they can still be modified by the class' own member functions (methods).
    – Simon B
    Apr 21, 2015 at 13:12
10

I think the term "state" (as opposed to a concrete type of state such as "member variable") is most useful when comparing a stateful API to a stateless one. Trying to define "state" without mentioning APIs is a bit like trying to define "variable" or "function" without mentioning programming languages; most of the correct answers only make sense to people who already know what the words mean.

Stateful vs Stateless

  • A stateful API is one that "remembers" what functions you've called so far and with what arguments, so the next time you call a function it's going to use that information. The "remembering" part is often implemented with member variables, but that's not the only way.
  • A stateless API is one where every function call depends solely on the arguments passed to it, and nothing else.

For example, OpenGL is probably the most stateful API I know of. If I may ludicrously oversimplify it for a moment, we might say it looks something like this:

glSetCurrentVertexBufferArray(vba1);
glSetCurrentVertexBufferObject(vbo1);
glSetCurrentVertexShader(vert1);
glSetCurrentFragmentShader(frag1);
// a dozen other things
glActuallyDrawStuffWithCurrentState(GL_TRIANGLES);

Almost every function is just used to pass in some of the state OpenGL needs to remember, then at the end you call one anticlimactically simple function to do all the drawing.

A stateless version of (oversimplified) OpenGL would probably look more like this:

glActuallyDrawStuff(vba1, vbo1, vert1, frag1, /* a dozen other things */, GL_TRIANGLES);

You'll often hear people say that APIs with less state are easier to reason about. If you can keep the argument count under control, I generally agree with that.

Mutable vs Immutable

As far as I know, this distinction is only meaningful when you can specify an initial state. For example, using C++ constructors:

// immutable state
ImmutableWindow windowA = new ImmutableWindow(600, 400);
windowA = new ImmutableWindow(800, 600); // to change the size, I need a whole new window

// mutable state
MutableWindow windowB = new MutableWindow(600, 400);
windowB.width = 800; // to change the size, I just alter the existing object
windowB.height = 600;

It would be hard to implement a window class that doesn't "remember" what size it is, but you can decide whether the user should be able to change a window's size after creating it.

P.S. In OOP it's true that "state" usually means "member variables", but it can be a lot more than that. For instance, in C++, a method can have a static variable, and lambdas can become closures by capturing variables. In both cases those variables persist across multiple calls to the function and thus probably qualify as state. Local variables in a regular function may also be considered state depending on how they're used (the ones I have up in main() often count).

1
  • AWESOME answer. Thank you so much, you really helped me pick this up fast. Little did I know, I've been working with this for a long time and didn't know what it was called.
    – the_endian
    Dec 8, 2016 at 3:49
3

In layman words

The dictionary states:

a. A condition or mode of being, as with regard to circumstances.

  1. state - the way something is with respect to its main attributes;

The state of something is the set of values that its attributes have in any given moment.

In OOP the state of an object is a snapshot of what its attributes' values are in any given moment.

Thing t = new Thing();
t.setColor("blue");
t.setPrice(100)
t.setSize("small");

The state of it is its color being blue, its price being 100 and its size being small.

If you later do:

t.setColor("red");

You change one of its attributes but you also changed the state a whole since the object is no longer the same as it was.

Sometimes classes are designed so their properties' values cannot be changed after it is created. All values of their properties are either passed to the constructor or read from some source like a database or a file, but there is no way to change those values after that moment, since there are no "setter" methods, or any other way of changing the values inside the object.

Thing t = new Thing("red",100,"small");
t.setColor("blue") -->> ERROR, the programmer didn't provide a setter or any other way to change the properties values after initialization.

That's called a state that cannot be changed of mutated. All you can do is destroy the object, create a new one and assing it to the same reference or variable.

Thing t = new Thing("red",100,"small");
t = new Thing("blue",100,"small");
// I had to create a new Thing with another color since this thing is inmutable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.