C # in-depth discussion of the two development principles

Source: Internet
Author: User

Use attributes to avoid direct exposure of data members to the outside world

When I was studying. net in the early days, I often encountered some friends who learned C #/. NET and asked what to do with attribute-based flashy things? Later, when I was working on a project, I often received complaints from people in the team. Why not put a public field directly? For example:

Class card
{
Public string name;
}

Do I have to make a private field + public attribute?

Class card
{
Private string name;
Public string name
{
Get {return this. Name ;}
Set {This. Name = value ;}
}
}

I remember that in an early project, a friend in the team was tired of writing private fields and public attributes, especially when encountering a lot of bloated data object classes, simply write a small tool to provide the field name and type of a class, and then automatically generate the corresponding private field + public attribute for the class.

I was a thoroughly practical programmer during programming. In a little more elegant words, I called it "I don't like design too much ". If I really want to write a card as above, and there is no need to change it in the future, I do not like the above section 2ndProgramThis makes things complicated on purpose. However, from the component perspective, there will always be some classes that will be used by the outside for a long time and may be changed in the future. At this time, it is necessary to provide attributes.

This is the reason why this item tries to generalize the attributes:

1. You can verify the value assignment or perform additional processing.

2. Thread Synchronization is supported.

3. You can use virtual or abstract attributes.

4. attributes can be placed in interfaces.

5. Get-only or set-only versions can be provided, and different access permissions can be provided for reading and writing (C #2.0 is supported)

I personally think 3 and 4 are the biggest advantages of attributes. They can fill in the defects of "virtual fields" or "abstract fields" and are very useful when designing components, it also reflects the spirit of the component-oriented language such as C.

However, if there is no such reason and it is more likely to make major changes to the program in the future, I don't have to turn every public field into a property. For example, when designing some lightweight struct for interoperability, it is no good to directly use the public field. Therefore, it seems that the use of "always use properties instead of accessible data members" in this entry is too tough.

In fact, the discussion here also shows what you need to pay attention to when reading Objective C #, that is, the objective principle is not universally applied. Different projects (projects with high componentization and reusability? Or "one-time writing, run for N years" Project), different roles (Class Library/component developers? Or application developers ?), There are different valid principles. In fact, many items in the book are considered from the perspective of class libraries/component developers.

We need to talk about the performance of attributes. If you simply use attributes in an access mode, there will be no performance loss to a considerable extent. This is because inline processing has been performed during JIT compilation. However, there are still some basic conditions for inline processing. In some cases, the JIT compiler does not use inline, such as virtual calls and the Il of methods.CodeThe length is too long (currently, the CLR rule is that the code length exceeds 32 bytes), complex control flow logic, and exception handling. These conditions are either unable to use inline (such as virtual attributes) at all, or the cost of inline is too high, which may easily lead to code bloat, or it may take a lot of time to get inline-it has lost the meaning of inline, because. net inline mechanism occurs in the JIT process. The use of attributes is uncomfortable. For example, it affects the development efficiency of developers, but does not affect the code running efficiency.

Usage of value type and reference type

This clause discusses tradeoff during type design-whether to design the type as a structure or a class. Mr. Bill wner gave the principle that "value types are used to store data, and reference types are used to define behavior (value types store values and reference types define behavior )".

To judge the applicability of this principle, Bill Wagner also provides a method to answer the following questions:

1. is the primary role of this type used for data storage?

2. Does this type of public interface have some access attributes?

3. Are you sure this type can never be a subclass?

4. Are you sure this type will never have polymorphism?

If the answer to all questions is yes, the value type should be used. This judgment does have a good reason to support it, but I personally think that "yes" is not enough to make up all the reasons for using the value type. In many project practices, I find that the performance problems caused by value types cannot be underestimated. There are two major performance problems caused by value types:

1. The box/Unbox caused by the conversion between the value type instance stack and the managed stack, and the resulting garbage on the managed stack.

2. By default, the value type uses the copy semantics of values. If it is a large value type, it also brings performance problems when passing parameters and function return values.

With regard to article 1st, Bill Wagner mentioned in the terms that "reference types impose a burden on the garbage collector" appears to be a correct judgment. However, due to the box/Unbox effect, in some cases, the value type has brought more burden to the garbage collector. For example, you can place some value types in a collection and then perform read/write operations on them frequently. If this happens, I think it is not a better way to "discard the structure and adopt the class. In fact, adding a value type (such as system. Drawing. Point) for data storage to a collection (system. Collections. arraylist) is a very common operation. However, the new generic technology introduced in C #2.0 has greatly improved the problem of box/Unbox.

For the first article, Mr. Scott Meyers tries his best to use pass-by-reference (Transfer address) and less pass-by-value (transfer value) in the first article of Objective C ++). Although the structure type in C # has the default deep copy semantics, there is no copy constructor call. In addition, the structure type does not have child classes. Therefore, to some extent, there is no polymorphism, and there is no slicing effect that may occur when the C ++ object transmits values. However, the cost of copying values is not small. Especially when the value type is large, the problem is serious. In fact. in the design guidelines for class library developers document of the. NET Framework, a principle is mentioned when the structure type should be used (there are other parallel principles) -- The data size of the Instance type must be smaller than 16 bytes. This document is mainly based on the operational efficiency of the type, while Mr. Bill wner's terms here are mainly based on the design of the type.

From the two discussions above, I personally prefer to adopt a more conservative design strategy for the structure type. Classes can be actively and boldly used. Because the Adverse Effects of "Designing a structure type unsuitable for a class" are far less than those of "Designing a class unsuitable for a structure type. In my current experience, I even think that only dealing with non-hosted interoperability is the best reason for using the structure type. In other cases, we should "Think Twice ". Of course, after the introduction of generic technology in C #2.0, box/Unbox will no longer be a heavy burden. To cope with some very lightweight occasions, the structure type still has its own place.

 

-----------ArticleFrom the network, copyright ownership Original Author

Related Article

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.