rockstar - mutability Flashcards
Immutable objects
- Once created, remain unchanged throughout their lifetime
- Data can’t be changed
- If data is changed: Old data is discarded and new data is created
What’s the difference between System.String and System.Text.StringBuilder classes?
- System.String is immutable
- System.StringBuilder is mutable
What’s the advantage of using System.Text.StringBuilder over System.String?
- System.StringBuilder is better for when there is a lot of string manipulation
- Otherwise, new strings are made every time there is a change
Why is immutability important in programming?
- Mutation hides change, which create (unexpected) side effects
- Makes code thread-safe
e.g. If another thread invokes color.set after Statement 1 but before Statement 2, the value of myColorInt won’t match the value of myColorName
int myColorInt = color.getRGB(); //Statement 1
String myColorName = color.getName(); //Statement 2
How can you create an immutable class in C#?
- Make all fields private / readonly
- Avoid exposing any methods that can modify the internal state
- If properties are needed, only getters and no setters
- Ensure that any modification operation returns a new object instead of modifying the current one
What is the readonly keyword in C#?
- Keyword that makes sure a field can only be assigned a value at the time of declaration
What are the advantages of using immutable objects in multi-threaded applications?
- Immutable objects cannot change their state after creation
- Eliminates the need for locks or synchronization mechanisms
What are the potential downsides of using immutable objects?
- Immutable objects create new instances when modifications are made
- Leads to increased memory usage if not managed properly
- Can affect performance in scenarios where object creation is frequent
How can you achieve immutability for collections in C#?
- Using methods like .AsReadOnly()
What is object pooling, and how does it relate to immutability?
- Technique where objects are reused instead of created and destroyed frequently
- Can be used to mitigate the performance impact of creating new objects by reusing existing ones when possible
Can you explain the difference between value types and reference types in the context of immutability?
- Value types like ‘structs’ are mutable because their state cannot be changed
- Reference types like ‘classes’ are mutable by default, but can be immutable through proper design
Immutable data types
- String
- DateTime
- Enum
- Int, double
- Boolean
Mutable data types
- List
- Dictionary
- Queue
- Stack
- StringBuilder
- Custom classes