Objective C # Reading Notes-entry 14: Minimize repeated initialization Logic

Source: Internet
Author: User

Constructor is used to initialize all the members of an object. It is a very common scenario for a class to have multiple constructor functions. All these constructor functions will inevitably have similar and even the same logic, in addition, with the increase of member variables and feature changes, the number of constructor will also increase. Many developers usually write a constructor first, and thenCodeCopy and paste it to other constructors to support multiple rewrite constructors defined on class interfaces. in fact, we should not do this. When we find that multiple constructors contain similar logic, we can extract them into a common constructor. In this way, you can avoid code duplication or use the constructor (Constructor initializer) Generate more efficient target code.

 

Reading directory:

1. the constructor calls each other directly.

2. Use default parameters to reduce code

3. Common constructor vs common auxiliary methods

4. Operation Process of CLR constructor type instance

5. Section

6. Further reading and reference

 

1. Mutual calls between constructors

The constructor allows one constructor to call another constructor. Mutual calls between constructors can effectively reduce repeated code. The following is a simple example of mutual calls between constructors:

 1   Public   Class  Myclass  2   {  3       Private List < String > Coll;  4       Private   String  Name;  5      6       Public Myclass (): This ( 0 , ""  )  7   {  8   }  9       10       Public Myclass ( Int Initialcount ): This (Initialcount,String  . Empty)  11   {  12   }  13       14       Public Myclass ( Int Initialcount, String  Name)  15   {  16 Coll = (initialcount> 0 )?New List < String > (Initialcount ): New List < String > ();  17           This . Name = Name;  18   }  19 }

 

2. Use default parameters to reduce repeated code

We can also further reduce repeated code in the constructor by using the default parameter, a new feature of C #4.0. We can unify the above Code into one constructor and specify the default value for all optional parameters. If you want to use overload to enumerate the same number of functions in the above Code, you must provide at least four constructors: one with no parameter and one with the initialcount parameter, one accepts the name parameter (called using the name parameter) and the other accepts both the initialcount and name parameters. You can see:

As the number of parameters increases, the required overload will also rise.The use of default parameters can effectively reduce the repeated code of the constructor, which is a good mechanism to avoid excessive overloading.

 1       Public   Class  Myclass  2   {  3           Private List < String > Coll; 4           Private   String  Name;  5           Private   String  P;  6   7           Public  Myclass ()  8 : This ( 0 , String . Empty)  9   {  10   }  11   12           //  The constructor uses optional parameters. Here, the name parameter uses "" instead of empty, which is more semantic. Because empty is not a compiler constant, it cannot be used as the default parameter.  13           Public Myclass ( Int Inititalcount = 0 , String Name = "" )  14   {  15 Coll = (inititalcount> 0 )? New List < String > (Inititalcount ): New List < String > ();  16               This . Name = Name;  17  }  18 }

Using the default parameters or providing multiple overloaded constructors is worth balancing (see Objective C # Reading Notes 10 ). In the preceding example, only the optional parameter constructor can be used to meet our requirements. Here, a non-argument constructor is retained because new () is used () the constrained generic class does not support constructors with default values. To meet the new () constraint, the class must provide the displayed non-argument constructor.

 

3. Common constructor vs common auxiliary methods

The default parameter is a new feature of C #4.0. in C # versions earlier than 4.0, you must compile each required constructor. This means a lot of repetitive code. In this case, we can use the constructor chain to let one constructor call another constructor declared in the same class, instead of creating a public auxiliary method like C ++-creating a public auxiliary method will impede the compiler from optimizing the code. Let's look at the following code (not good ):

View code

 1   Public   Class  Myclass  2   { 3       Private List < String > Coll;  4       Private   String  Name;  5   6       Public  Myclass ()  7   {  8 Commonconstructor ( 0 ,""  );  9   }  10   11       Public Myclass ( Int  Initialcount)  12   {  13 Commonconstructor (initialcount, ""  );  14   } 15   16       Public Myclass ( Int Initialcount, String  Name)  17   {  18   Commonconstructor (initialcount, name );  19   }  20   21       ///   <Summary> 22       ///  An auxiliary method public to all Constructors  23       ///   </Summary>  24       ///   <Param name = "count"> </param>  25       ///   <Param name = "name"> </param>  26       Private   Void Commonconstructor ( Int Count, String  Name)  27   {  28 Coll = (inititalcount> 0 )? New List < String > (Inititalcount ): New List < String > ();  29           This . Name = Name; 30   }  31 }

 

The above class uses a constructor public auxiliary method, similar to the previous example using default parameters, except that one is a call between constructor functions, one is to use public auxiliary methods. However, during compilation, the compiler adds a series of code to the example using the Helper method version: All Member initiators (see Objective C # note 12 ), the base class constructor will also be called, so this reduces the code efficiency and throws a compilation error when we define the name field as readonly:

 Readonly Fields must be initialized in the Declaration or constructor.

Finally, we should know how to create a common constructor and provide a common number of auxiliary methodsDifferencesIs:

The compiler does not generate code that calls the base class constructor multiple times, nor copy the instance variable inspector to each constructor. The base class constructor is called once by the last constructor: the constructor can define only one constructor, or use this () to delegate to another constructor, either base () can be used to call the constructors of the base class.

 

4. process of constructing a type instance using CLR

Creation typeFirst InstanceOperation Sequence diagram:

InSecond and later instancesIt will start directly from step 5, because the class constructor executes only once and step 7 of Step 6 will be optimized so that the constructor can remove repeated commands from the compiler, the execution sequence is as follows:

 

5. Section

The C # constructor can be used to extract these public logics. You only need to write them once and execute them once.Whether to use the default parameter or provide multiple constructors for overloading depends on the specific use scenario. Generally, you should use the default parameter for a public constructor, the default parameter value must always be reasonable and cannot throw an exception. At the same time, we need to ensure that each member variable is initialized only once during the instance construction process. The best way to achieve this is to initialize the variable as early as possible.Initialize simple resources with the initializer, use the constructor to initialize members that require complex logic, and extract the repeated logic of constructor to a common constructor to reduce repeated code..

 

References & further reading

Named real parameters and optional Real Parameters

New Constraint

Type parameter Constraints

Readonly (C # reference)

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.