Negative tive C # item7: implement the value type as constant and atomic as much as possible.

Source: Internet
Author: User

When creating a value type instance, we should try to implement it as constant and Atomic. The so-called constant, that is, the object will not be changed after it is created, similarProgramA constant defined in. Once a value type is created, it can be regarded as a constant state. In this way, it is thread-safe.

Atomicity refers to some correlated fields in the value type, such as birthdate and age. Age is calculated based on birthdate. if the object is used only to modify the age, without changing the birthday, the result is obviously incorrect. All atomic types are single entities. We need to maintain the associated fields at the same time.

The following two steps can be taken to construct a constant value type: 1) Declare the private field in the type as readonly; 2) set the attribute in the type to read-only, deletes the Set Method of the attribute.

It should be noted that in the process of converting the value type to the constant type, the so-called constant is the data stored by the pointer in the "stack, for data stored in the "Heap", it is not enough to simply use readonly settings. Here the "constant" only indicates that the memory address pointing to the "Heap" will not change, we can change the value in the corresponding memory in other ways. To solve this problem, we need to make defensive copies of the data in the "heap.

There are usually three ways to initialize the constant type:

  1. Provides a suitable constructor set.
  2. Create by using the factory method.
  3. Provides a helper class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.