Designing Efficient Immutable .Net 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 

Get Currently Executing Assembly’s Directory

Sometimes it becomes necessary to find out the directory where the current executing assembly is running. Among several ways to do the task  , the following code–snippet can be employed  to return the absolute location of the loaded file that contains the manifest:

using System.Reflection;
string currentAssemblyDirectoryName = Path.GetDirectoryName(
Assembly.GetExecutingAssembly()
.Location
);
view raw gistfile1.cs hosted with ❤ by GitHub

Beware that Assembly.Location property returns the location of the assembly file after it is shadow-copied. In addition , if it is dynamically loaded using Load method, it returns empty string .

As stated in the comments below, if you are interested in retrieving the location of the assembly before it is shadow-copied or loaded,  use Assembly.CodeBase property instead. Please note that, it is the location specified originally while stating the AssemblyName.

Preparation for Exam 70-503 TS: Microsoft .NET Framework 3.5 – Windows Communication Foundation

Just sat for the exam 70-503 TS:  Microsoft .NET Framework 3.5 – Windows Communication Foundation yesterday. It was really fun to sit for the beta exam though it was pretty long – 64 questions in Three hours and thirty minutes. Unfortunately  result  has not been published yet .According to Prometric, I will get the result 8 weeks before MS will be releasing the Final version of the exam.

After finishing the exam, I got the idea how to score good in that exam  ABC : Address , binding and contract . If you have solid understanding in these three pillars of WCF – you will surely score well. These are the topic where you should have solid understanding before sitting for the exam –

1.       WCF service and client configuration – not using service configuration tool provided in windows sdk , rather thorough Xml.

2.       Security related configuration – Authentication and Authorization support in WCF thorough xml configuration.

3.       Service Instance – Single ,PerCall , PerSession and Thread-safety of the instance.

4.       Session and Transaction.

5.       Duplex channel.  WsDualHttpBinding.

6.       Serialization.

7.       Instrumentation of WCF service instance.

8.       Interoperability with ASMX.

Thanks for visiting the blog. Wish you luck in the Exam. J

Inside .Net readonly

The common language runtime in .Net Framework supports two kind of fields – readonly and read/write fields. As name suggests, value in the read/write fields can be assigned as many times as one wants; On the other hand, value in the readonly field can not be changed after it get initialized in type/instance contructor of the type containing the readonly.

Depending on the type of the readonly field – static/intance– it gets initialized. Static readonly gets loaded when the dll containing the class being loaded by CLR where as  instance readonly field got initialized when the constructor get called for the particular instance. In the following code – Bullet1 gets initialized when the InsideReadonly first gets loaded in CLR –

public class InsideReadonly
{

     public static readonly string Bullet1 = “\u2022”;

}
 

Whereas Bullet1 gets initialized when InsideReadonly readonlyObject = new InsideReadonly(); line get executed –

public class InsideReadonly
{       
     public readonly string Bullet1 = “\u2022”;
}

The versioning problem that I discussed in my last post- Inside .Net Constants(https://adilakhter.wordpress.com/2007/12/09/inside-net-constants/) can be easily solved by using one of the above code block replacing the constant with readonly. Changing the value of the readonly field Bullet1 with a new value and building the .dll makes the application load the new values , given that versioning policy of the .DLL assembly always add the newer version / the assembly is not strongly typed.

By saying all these, I would like to make one point about the readonly fields – whenever we want to use it – we need to keep in mind that, the value of the readonly field only can be ONLY assigned in either in variable declaration or in type/instance constructor –  

public class InsideReadonly
        {
            public readonly string Bullet1 = “\u2022”;            
           
public InsideReadonly()
            {
                Bullet1 = “Changed Bullet1”;//Allowed                
                
Bullet1 = “Changed Bullet11111”;//Allowed
            }
            public void TestChangeReadonly()
            {
                Bullet1 = “Change is not allowed”;// Not allowed
            }
        }
 

Design a site like this with WordPress.com
Get started