Immutable

Eintrag zuletzt aktualisiert am: 07.11.2016

Ein Immutable ist eine Datenstruktur, deren Inhalt sich nicht ändern lässt. Eine Änderungsoperation auf ein Immutable liefert allenfalls ein neues Objekt zurück.

Implementierungsbeispiele

ImmutableJS für JavaScript: http://facebook.github.io/immutable-js
Immutable Collections in .NET: https://www.nuget.org/packages/System.Collections.Immutable

Beispiel: Immutable Collections in .NET

using System.Collections.Immutable;

var orte1 = ImmutableList<string>.Empty;
var orte2 = orte1.Add("Essen");
Console.WriteLine("Orte1: " + orte1.Count); // 0
Console.WriteLine("Orte2: " + orte2.Count); // 1
var orte3 = orte2.Add("Bochum");
Console.WriteLine("Orte1: " + orte1.Count); // 0
Console.WriteLine("Orte2: " + orte2.Count); // 1
Console.WriteLine("Orte3: " + orte3.Count); // 2
orte3 = orte3.Add("Dortmund");
Console.WriteLine("Orte3: " + orte3.Count); // 3

// besser:
var orte4 = ImmutableList<string>.Empty.AddRange(new[] { "Essen", "Bochum" });
var orte5 = orte4.AddRange(new[] { "Dortmund", "Duisburg" });
Console.WriteLine("Orte4: " + orte4.Count); // 2
Console.WriteLine("Orte5: " + orte5.Count); // 4

var orte6 = orte5.Remove("Duisburg");
Console.WriteLine("Orte4: " + orte4.Count); // 2
Console.WriteLine("Orte5: " + orte5.Count); // 4
Console.WriteLine("Orte6: " + orte6.Count); // 3