Adil Akhter

on software engineering

Designing Efficient Immutable .Net2.0 Objects

What is an immutable object?

By definition immutable object is the object whose state can not be changed after it is created. That means, after creating the object, its publicly exposed members can not be changed from their initial assigned values. On the contrary, mutable objects are objects whose state can be changed at any point of time.

Every developer has to take a important decision whether to make a class mutable or immutable while designing the domain model.
While taking this decision, careful considerations can make us avoid the potential pitfall of using immutable object. 
 Why & How using immutable .Net object – is our today’s discussion. Let’s begin with How part . 

How to implement .Net Immutable Object?

 The way I would implement an immutable .Net class –           

-          Make the fields private readonly.
-          Provide a Public property with get accessor.
-          If the class is no longer needed to inherited – making it sealed. 

Like in the following example, I am implementing an immutable class  UserContact which will be inherited in User  

classdiagram1.jpg

 Here is the Implementation of the Immutable classes –     

    public class UserContact

    {

        private readonly string _Name;

        public string Name   

        {

            get { return _Name; }

        }

        private readonly string _EmailAddress;

        public string EmailAddress

        {

            get { return _EmailAddress; }

        }

        public UserContact( string name , string emailAddress)

        {

            _EmailAddress = emailAddress;

            _Name = name;

        }

    }

UserContact get inherited by User as follows [Since User class is no longer inherited – we make it sealed] -

 

    public sealed class User : UserContact

    {

        private readonly string _UserName;

        public string UserName

        {

            get { return _UserName; }

        }

        public User(string name, string email, string userName)

            : base(name, email) { }

    }


So, isn’t it really easy to implement a Truly Immutable class in .Net framework? J Now the question pops into our mind – why we will be using immutable .net objects , what would be benefits of that ? Let’s explore that –  

 

 

Why use immutable object?

 Protection:

From the definition we know, Immutable objects can not be changed after its being initialized. So, while using inside application, immutable object can flow in different layers of the application without getting worried about being altered by different layers.  

Performance:

Copying object will be much easier, we just need to copy the reference instead of copying the whole object. It would be much faster to copy reference than the whole object.

User user = new User("adil", "adil.bd@hotmail.com", "adak");
User userTemp = user; 

In case of mutable object, we would need to create defensive copy of the object and in .Net term, we need to create a Deep Copy of object otherwise, changing a property in the actual mutable object would reflect everywhere where the object is referenced. For example, let’s consider User as mutable; then changing any thing in user object will have same impact on userTemp as well which is not intended.

To avoid this situation, in case of mutable object, we need to make a Deep Copy of the object which is a costly operation. However, for immutable object, copying the reference would be enough since its state can’t be changed. 

Scalability:

Thread synchronization is an issue of concern while designing multithreaded application. Overhead of synchronizing immutable object is far less than mutable object. By default , an individual immutable object does not need to be synchronized as its state will be not be modified by any thread. However, since the immutable object will still be accessed thorough reference , it would require some synchronization. In complex sync scenarios, immutable object would perform far better then mutable version.   

Consistency: 

If we consider inheritance hierarchy, immutability provides a way for the sub-class to maintain consistency in inheritance hierarchy. Consider following mutable objects–

 

classdiagram2.jpg

When we instantiate the StudentMutable object, the AccountType is automatically set to Student Account –

public StudentMutable(string name , string email , string userName )
: base(name ,email , userName,"Student Account"){}

 Now, we can write following lines by which the AccountType property could be anything other than "Student Account” which is completely inconsistent -   

StudentMutable mutable = new StudentMutable("Adil", "Adil.bd@hotmai.com", "adil");   
mutable.AccountType = "whatever account";   

But if we use Immutable object in inheritance – the object hierarchy will always be consistent.:) 

 

 

What to consider while designing Immutable objects?

Intantiation of immutable object might be considered an operation that will be done more frequently. Then the allocation and freeing the resource for the immutable object would be the most recurrent opertaion which might result as performace overhead. Incase of regular objects , it seems that syncronization is far more costly operation from CPU perspective than allocating and freeing resource.  

For objects that require significant time to initialize , we may consider to implement Object Pool or Flyweight pattern to enhance reusability.  

Conclusion

 So , We can achive much faster and efficient code if we use Immutable object. But by saying all this , definitly we need to design accordingly and carefully so that immutable object can perform to its best. In this article , we learn how to implement immutable object in .Net and what’s its benefits and what we need to consider while implementing immutable object. In my next post , I am thinking to write something about reusing the immutable object to enhance efficiency. Thanks for visiting the the blog. Let me know your comments and feedbacks. Bye J .  

kick it on DotNetKicks.com

Comments

Nullable said:

Nicely said. That's more of an article than a blog post (meaning much better quality than a typical blog post). Have you thought of writing articles? I'd love to have you on Eels.

# April 16, 2008 2:15 PM

Dong said:

can you modify the picture?i can't see it.

# April 17, 2008 2:11 AM

Adil Akhter said:

Hi Dong,

Thanks for visiting the blog.

Which picture you want me to change?

/Adil

# April 17, 2008 4:32 AM

Adil Akhter said:

Hi Nullable,

Thanks for visiting the blog.

I am really glad that you liked the post. And I will surely think about writing the artiles.

/Adil

# April 17, 2008 4:35 AM

wwfDev said:

Great post. Have you considered how to serialize immutable objects (like soap, webservice calls etc.)?

# April 21, 2008 6:43 AM

Adil Akhter said:

Hi wwfDev,

Hope you are fine. I will try to cover in my next post.

/adil

# May 4, 2008 2:06 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)