Understanding Mutability in OOP
Saidur Rahman Akash
Software Engineer @AKIJ iBOS Limited | .NET Core, C#, MSSQL
Mutability is closely related to object-oriented programming. When an object is created, if it cannot be modified afterward, we call it an immutable object. Have you encountered something like this before? If you’re a C# programmer, you’ve likely come across the difference between String and StringBuilder.
In C#, the String class is immutable, meaning once you create a String object, it cannot be modified (though you can assign a new String to the same variable). In contrast, StringBuilder is mutable. You can modify a StringBuilder object without creating a new instance.
If the idea isn’t entirely clear yet, let's explore it with a practical C# example.
Example 1: Immutable String
When you work with a String, any modification creates a new object, leaving the original one unchanged.
using System;
class Program
{
static void Main()
{
// String is immutable
string greeting = "Hello";
Console.WriteLine("Original String: " + greeting);
// Modifying the string creates a new object
greeting += ", World!";
Console.WriteLine("Modified String: " + greeting);
}
}
Explanation:
Example 2: Mutable StringBuilder
In contrast, StringBuilder allows you to modify the contents of an object without creating new instances.
using System;
using System.Text;
class Program
{
static void Main()
{
// StringBuilder is mutable
StringBuilder greeting = new StringBuilder("Hello");
Console.WriteLine("Original StringBuilder: " + greeting);
// Modify the StringBuilder in place
greeting.Append(", World!");
Console.WriteLine("Modified StringBuilder: " + greeting);
}
}
Explanation:
领英推荐
Why Does Mutability Matter?
-Memory Efficiency
-Performance:
Regardless of the language you're using, it’s essential to understand which data structures or objects are mutable and which are immutable. Not knowing this can lead to bugs that are hard to track down.
Conclusion
Knowing when and how to use mutable and immutable objects is crucial in programming. Different languages have their own data structures or libraries that define which objects are mutable or immutable. Make sure to familiarize yourself with these characteristics in the language you're using.
Understanding the differences and knowing when to use which will help you write safer, more efficient, and bug-free code.
The effectiveness of mutable and immutable objects in different scenarios has been beautifully discussed in this answer on StackOverflow.
Software Engineer @Akij iBOS Ltd || .NET, React
1 个月For more clarification, here are some other examples of Mutable and Immutable Mutable : List<T>, Dictionary<TKey, TValue>, and arrays? Immutable: DateTime, Tuple, string, and Record