Stateless vs Stateful and Mutable vs Immutable

Stateless means there is no memory of the past. Every transaction is performed as if it were being done for the very first time.

Stateful means that there is memory of the past. Previous transactions are remembered and may affect the current transaction.

      Stateless:
       //The state is derived by what is passed into the function
        function int addOne(int number)
        {
          return number + 1;
        }

        Stateful:
        //The state is maintained by the function
        private int _number = 0; //initially zero
        function int addOne()
        {
         return _number++;
        }

 

Mutable Objects: When you have a reference to an instance of an object, the contents of that instance can be altered.

Immutable Objects: When you have a reference to an instance of an object, the contents of that instance cannot be altered.

        Point myPoint = new Point( 0, 0 );//mutable
	System.out.println( myPoint );//print out 0, 0
	myPoint.setLocation( 1.0, 0.0 );
	System.out.println( myPoint ); //print out 1.0, 0.0

	String myString = new String( "old String" );//immutable
	System.out.println( myString );//print out old String
	myString.replaceAll( "old", "new" );
	System.out.println( myString );//print out old String

Ref:
1. http://programmers.stackexchange.com/questions/101337/whats-the-difference-between-stateful-and-stateless
2. http://www.javaranch.com/journal/2003/04/immutable.htm

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s