What is State, Mutable State and Immutable State?

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

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

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

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

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

What is State, Mutable State and Immutable State?

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

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

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

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

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật