GuillaumeSalles / redux.NET

Redux.NET is a predictable state container for .NET apps. Inspired by https://github.com/reactjs/redux.
712 stars 86 forks source link

How to mutate the immutable state without a lot of mess and boilerplate #30

Open lanwin opened 8 years ago

lanwin commented 8 years ago

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.

GuillaumeSalles commented 8 years ago

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.

    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 };
        }
    }

If those tips help you, I will update the readme in the few next days.

GuillaumeSalles commented 8 years ago

Maybe you will find the last C# 7 design notes interesting.

GuillaumeSalles commented 7 years ago

The new C# records could be useful to build an immutable state without boilerplate !

xaviergonz commented 7 years ago

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.