Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Immutable Collection

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you the "sample analysis of the Immutable collection", the content is simple and clear, hoping to help you solve your doubts, let the editor lead you to study and study the "sample analysis of the Immutable collection" this article.

An immutable set, as its name implies, means that the set is immutable. The data items of the collection are provided at creation time and are immutable throughout the lifecycle.

Why use immutable objects? The immutable object has the following advantages:

For unreliable customer code libraries, it uses security and can safely use these objects in untrusted class libraries

Thread-safe: immutable objects are safe under multithreading and have no race condition

There is no need to support variability, so you can save space and time as much as possible. All immutable set implementations use memory more efficiently than mutable sets (analysis)

Can be used as a constant and is expected to remain the same in the future

Immutable objects can naturally be used as constants because they are inherently immutable and are a good defensive programming technical practice for the use of immutable objects.

The Microsoft .NET team has officially released immutable collections, which can be added through Nuget, including the following immutable collections:

System.Collections.Immutable.ImmutableArray

System.Collections.Immutable.ImmutableArray

System.Collections.Immutable.ImmutableDictionary

System.Collections.Immutable.ImmutableDictionary

System.Collections.Immutable.ImmutableHashSet

System.Collections.Immutable.ImmutableHashSet

System.Collections.Immutable.ImmutableList

System.Collections.Immutable.ImmutableList

System.Collections.Immutable.ImmutableQueue

System.Collections.Immutable.ImmutableQueue

System.Collections.Immutable.ImmutableSortedDictionary

System.Collections.Immutable.ImmutableSortedDictionary

System.Collections.Immutable.ImmutableSortedSet

System.Collections.Immutable.ImmutableSortedSet

System.Collections.Immutable.ImmutableStack

System.Collections.Immutable.ImmutableStack

The documentation of MSDN refers to https://msdn.microsoft.com/zh-cn/library/system.collections.immutable.aspx, how to use it? Let's look at an example. Suppose you have established a billing system, and you need an immutable design so that you don't need to worry about data corruption in the case of multithreaded operations. For example, you need to print a snapshot of the data through a worker thread, which avoids blocking the user's editing operations and allows the user to continue editing without affecting printing.

The variable data model is as follows:

Class Order

{

Public Order ()

{

Lines = new List ()

}

Public List Lines {get; private set;}

}

Class OrderLine

{

Public int Quantity {get; set;}

Public decimal UnitPrice {get; set;}

Public float Discount {get; set;}

Public decimal Total

{

Get

{

Return Quantity * UnitPrice * (decimal) (1.0f-Discount)

}

}

}

Let's turn it into an immutable design:

Class OrderLine

{

Public OrderLine (int quantity, decimal unitPrice, float discount)

{

Quantity = quantity

UnitPrice = unitPrice

Discount = discount

}

Public int Quantity {get; private set;}

Public decimal UnitPrice {get; private set;}

Public float Discount {get; private set;}

Public decimal Total

{

Get

{

Return Quantity * UnitPrice * (decimal) (1.0f-Discount)

}

}

}

This new design requires you to create an order and create a new instance whenever any property value changes. You can update individual properties without explicitly calling the constructor by adding the WithXxx method:

Class OrderLine

{

/ /...

Public OrderLine WithQuantity (int value)

{

Return value = = Quantity

? This

: new OrderLine (value, UnitPrice, Discount)

}

Public OrderLine WithUnitPrice (decimal value)

{

Return value = = UnitPrice

? This

: new OrderLine (Quantity, value, Discount)

}

Public OrderLine WithDiscount (float value)

{

Return value = = Discount

? This

: new OrderLine (Quantity, UnitPrice, value)

}

}

This makes immutability easier to use:

OrderLine apple = new OrderLine (quantity: 1, unitPrice: 2.5m, discount: 0.0f)

OrderLine discountedAppled = apple.WithDiscount (.3f)

Now let's see how we can implement the invariance of the order. The Lines property is already read-only, but it refers to mutable objects. Because it is a collection, it can easily replace the ImmutableList transformation by simply replacing it:

Class Order

{

Public Order (IEnumerable lines)

{

Lines = lines.ToImmutableList ()

}

Public ImmutableList Lines {get; private set;}

Public Order WithLines (IEnumerable value)

{

Return Object.ReferenceEquals (Lines, value)

? This

: new Order (value)

}

}

This design has some interesting properties:

This constructor accepts IEnumerable and allows it to be passed in any collection.

We use the ToImmutableList () extension method to convert it to ImmutableList. If the instance is already an immutable list, it simply converts rather than creates a new collection.

The WithLines () method follows our order convention, and you can avoid creating a new instance if the new list is the same as the current list.

We can also add some convenient methods to make it easier to update order lines:

Class Order

{

/ /...

Public Order AddLine (OrderLine value)

{

Return WithLines (Lines.Add (value))

}

Public Order RemoveLine (OrderLine value)

{

Return WithLines (Lines.Remove (value))

}

Public Order ReplaceLine (OrderLine oldValue, OrderLine newValue)

{

Return oldValue = = newValue

? This

: WithLines (Lines.Replace (oldValue, newValue))

}

}

The code to supplement the order looks like this:

OrderLine apple = new OrderLine (quantity: 1, unitPrice: 2.5m, discount: 0.0f)

Order order = new Order (ImmutableList.Create (apple))

OrderLine discountedApple = apple.WithDiscount (discount)

Order discountedOrder = order.ReplaceLine (apple, discountedApple)

The advantage of this design is that it avoids unnecessary object creation as much as possible. For example, when the value of the discount is equal to 0.0f, even if there is no discount, discountedApple and discountedOrder refer to existing instances of Apple and orders.

This is because:

1.apple.WithDiscount () returns an existing instance of Apple because the new discount is the current value of the same discount attribute.

2.order.ReplaceLine () returns the existing instance if both arguments are the same.

Our immutable collection of other operations follows this maximization of reuse. For example, adding order lines to 1000 order lines and 1001 order lines does not create the entire new list. Instead, it will reuse a large chunk of the existing list. This is possible because the internal structure of the list is a tree that allows nodes to share different instances.

The above is all the content of this article "sample Analysis of Immutable Collection". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report