Make objects in session immutable in Java
<p>In a web based application we have an <code>User</code> object in the <code>session</code> for each logged in user.</p>

<p>The user is as below</p>

<pre><code>Class User {
    //With setter and getters
      private String userId,
      private String name,
      private Account Account,
 }

Class Account {
     //with setter and getters.
     private String accountNumber;    
 }
</code></pre>

<p>When the user logged in a session object is created for him and his <code>userId</code> ,<code>name</code> and <code>Account</code> will be set for him.</p>

<p>After that, every programmer can access the <code>session</code> and read user and his information. But it is possible that one programmer change the <code>Account</code> by mistake.</p>

<p>For example:</p>

<pre><code> 1. TrasnferVO = new TransferVO;
 2. TransferVO.setAccount( user.getAccount() );
 3. TransferVO.getAccount.setAccountNumber("foo");
 4. User user = getUserFromSession();
 5. user.getAccountNumber(); // Now I have foo
</code></pre>

<p>At line <strong>2</strong> a new <strong>copy</strong> of user account should be created and set to <code>TransferVO</code> because the the object reference is passed not its value! 
So the line <strong>3</strong> will change the user session account number. And we will lost the corrupted <code>accountNumber</code> in session.</p>

<p>Is there any guideline to handle it or every individual programmer must take care of it. </p>

<p>Of course this mistake can happen in every code in the project, but I am looking for a way to make the session object properties, which is very important, immutable.</p>