How to mutate the immutable state without a lot of mess and boilerplate
So far so good. But how would you create and mutate the immutable state in C# without creating a lot of mess and boilerplate?
A few suggestions in the readme would be fantastic.
Hello lanwin,
Unfortunately, I did not found a silver bullet to get immutability without boilerplate in C# 6. But I can tell you what we do and where we want to go with immutability at my job.
- We use https://www.nuget.org/packages/System.Collections.Immutable for collections.
- We chose to not be strictly immutable to avoid too much boilerplate. We use a constructor with a parameter of the same type to avoid to reset every properties for every "With... methods". (If I remember well I found this trick in the Roslyn sources (large .NET project that heavily use immutability)).
public class Customer
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public ImmutableList<Address> Addresses { get; private set; }
public Customer()
{
}
public Customer(Customer other)
{
this.FirstName = other.FirstName;
this.LastName = other.LastName;
this.Addresses = other.Addresses;
}
public Customer WithFirstName(string firstName)
{
return new Customer(this) { FirstName = firstName };
}
public Customer WithLastName(string lastName)
{
return new Customer(this) { LastName = lastName };
}
public Customer WithAddresses(ImmutableList<Address> addresses)
{
return new Customer(this) { Addresses = addresses };
}
}
- We use code snippets to generate "With... methods" faster. A code generator like the one used to generate the xaml.g.cs would be better... It would be awesome !
- A mutable state are usually spotted really fast through code review. If it is not enough, a custom Analyser could validate if a class is immutable or not and break the build if needed. We really did not need to go that far at my job.
- Wait for C# 7 immutable type ? https://github.com/dotnet/roslyn/issues/159
If those tips help you, I will update the readme in the few next days.
Maybe you will find the last C# 7 design notes interesting.
The new C# records could be useful to build an immutable state without boilerplate !
For anyone who is interested I made something to minimize the boilerplate needed when using redux (at least while C# doesn't implement it itself):
https://github.com/xaviergonz/T4Immutable T4Immutable is a T4 template for C# .NET apps that generates code for immutable classes.
As an extra note I just updated it to properly support properties that are collections. GetHashCode, Equals, etc will work OK as long as the collections are equivalent.