Stateless Object

A core idea of "Object-Oriented Design(OOD)",is that "every object has a state,and their member functions can change this state".

However, It isn't right in some case.

for example,most of functors in STL(Standard Template Library) do not have any member variables,e.g.std::minus .The structure of these class is very very simple. It has no member variable,only one member functions,and when ever you execute this function,with same arguments,you'll get the same answer. So we say these objects are stateless. The only distinguish of two object instance of a same class,is their memory locations.(That's why objects which have no member variables have a size 1,we need a way to distinguish them).

And,we can modify our design,so that every class has no no member variables.Are they truly is stateless?
e.g,assume that we have a such class

class Widget{
    ///register this widget to system
    ///unregister this widget 
  int height;
  int length;

  ///called when size changed.
  void OnResize(){
    ///refresh this window.

We can simply save it's member variables,the value of height and length,to a file,and restore these values from file another time.However,we'll found we had succeeded restore these values,but the size of the widget does not changed. Why?

Because there are states of this widget outside this class.So having no member variables doesn't mean stateless.

In other words,we can modify the implementation of the above class,(only the implementation,not the interface),so that it has no member variables,we'll let another object save these. What's the advantage of this?

First,we divide the data manipulation and data store into 2 classes.we can design multiple data store stage for the same class,which is often called "policy-based design".

And the second,we can store all states of all objects into only one object.If we have many instances of a same class,if we need shift the object between states,this should be more efficient.for instance,if we want to erase the content of a string,we do not need really truncate the memory it used,just change it's pointer to point to a empty string!And if we want to undo this operation,(oh my god,this is a hard work),we only need to save the last state in the last operation,(the pointer before erase),and restore it.In all of their member functions ,we just change the pointer between instances,and create new instance when needed.(policy of "copy on write",an important design patten).

And because we are C++ programmers, ,we have template,we have generic tuples, we have type lists ,we have generic design patten implantations,we have...we have the sunshine from the God!