Saturday, 5 September 2020

C# - Stateful vs Stateless


Stateful vs Stateless

·         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.
·         stateless API is one where every function call depends solely on the arguments passed to it, and nothing else.

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.

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.
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).


No comments:

Post a Comment