官术网_书友最值得收藏!

Immutable objects and data structures

Immutable types are normally thought of as just value types. With value types, it makes sense that when they are set, you don't want them to change. But you can also have immutable object types and immutable data structure types. Immutable types are a type whose internal state does not change once they have been initialized.

The behavior of immutable types does not astonish or surprise fellow programmers and so conforms to the principle of least astonishment (POLA). The POLA conformity of immutable types adheres to any contracts made between clients, and because it is predictable, programmers will find it easy to reason about its behavior.

Since immutable types are predictable and do not change, you are not going to be in for any nasty surprises. So you don't have to worry about any undesirable effects due to them being altered in some way. This makes immutable types ideal for sharing between threads as they are thread-safe and there is no need for defensive programming.

When you create an immutable type and use object validation, you have a valid object for the lifetime of that object.

Let's have a look at an example of an immutable type in C#.

An example of an immutable type

We are now going to look at an immutable object. The Person object in the following code has three private member variables. The only time these can be set is during the creation time in the constructor. Once set, they are unable to be modified for the rest of the object's lifetime. Each variable is only readable via read-only properties:

namespace CH3.ImmutableObjectsAndDataStructures
{
public class Person
{
private readonly int _id;
private readonly string _firstName;
private readonly string _lastName;

public int Id => _id;
public string FirstName => _firstName;
public string LastName => _lastName;
public string FullName => $"{_firstName} {_lastName}";
public string FullNameReversed => $"{_lastName}, {_firstName}";

public Person(int id, string firstName, string lastName)
{
_id = id;
_firstName = firstName;
_lastName = lastName;
}
}
}

Now we have seen how easy it is to write immutable objects and data structures, we will look at data and methods in objects.

主站蜘蛛池模板: 贵阳市| 辽中县| 平凉市| 安平县| 揭东县| 遵义县| 封开县| 炉霍县| 贺州市| 松阳县| 米泉市| 益阳市| 象州县| 邵武市| 土默特左旗| 贵定县| 平度市| 武山县| 博爱县| 同德县| 方正县| 菏泽市| 蒙山县| 定结县| 观塘区| 饶阳县| 马尔康县| 桂东县| 阳新县| 明溪县| 集贤县| 日喀则市| 普兰县| 准格尔旗| 远安县| 喀喇| 阳东县| 阳新县| 庄浪县| 原平市| 将乐县|