- Clean Code in C#
- Jason Alls
- 360字
- 2021-06-18 18:28:10
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.
- 大學計算機基礎(第二版)
- 自然語言處理實戰:預訓練模型應用及其產品化
- WebAssembly實戰
- 碼上行動:零基礎學會Python編程(ChatGPT版)
- 軟件測試項目實戰之性能測試篇
- 網頁設計與制作教程(HTML+CSS+JavaScript)(第2版)
- Java網絡編程實戰
- C語言程序設計
- Python預測之美:數據分析與算法實戰(雙色)
- INSTANT Premium Drupal Themes
- Yii2 By Example
- Visual FoxPro數據庫程序設計
- Tkinter GUI Application Development Blueprints
- Scratch超人漫游記:創意程序設計:STEAM創新教育指南
- 寫給所有人的編程思維