Clause 4: Use the conditional feature instead # If condition Compilation

Source: Internet
Author: User

# If/# endif condition compilation usually comes from the same copySource codeGenerate different result files. The most common ones are debug and release. However, these tools are not very handy in specific applications, because they are too easy to abuse and used to createCodeIt is usually difficult to understand and debug. C # Language designers use better tools to create different machine codes for different environments. C # added a conditional feature for this purpose,This feature can indicate whether a method should be called in an environment setting. Using this method to describe Conditional compilation is clearer than # If/# endif. Since the compiler understands the conditional feature, it can better verify the code when the conditional feature is applied. The conditional feature is applied at the method level, so it requires us to express the conditional code in the unit of method. To create a conditional code block, we should use the conditional feature to replace the traditional # If/# endif.
MajorityProgramVeteran engineers have used Conditional compilation to check the prerequisites and post-conditions of objects. For example, writing a private method to check the non-variant of all classes and objects (invariant: to ensure that the nature of classes or objects is not broken, however, a set of conditions are used to verify its own status .), Then, compile the conditional method so that it only appears in the debug version program.

Private   Void Checkstate ()
{
// Honest practices:
# If Debug
Trace. writeline ("entering checkstate
For Person ");
// Obtain the name of the function being called:
String Methodname =  
New Stacktrace (). getframe ( 1 ). Getmethod (). Name;
Debug. Assert (_ lastname
! =   Null , Methodname,
" Last name cannot be null " );
Debug. Assert (_ lastname. Length
>   0 , Methodname,
" Last name cannot be blank " );
Debug. Assert (_ firstname
! =   Null , Methodname,
" First name cannot be null " );
Debug. Assert (_ firstname. Length
>   0 , Methodname,
" First name cannot be blank " );
Trace. writeline (
" Exiting checkstate for person " );
# Endif
}

Conditional compilation # If and # endif make the checkstate () in the final release version an empty method, but it will be called in both release and DEBUG Versions. In release, checkstate () does nothing, but we must pay for method loading, JIT compilation, and calling.
In terms of correctness, this approach is generally not a problem, but sometimes it may cause a strange bug in the release version. The following code demonstrates the common errors that may occur when the # If and # endif conditions are used for compilation:

Public   Void Func ()
{< br> string MSG = null ;< br> # If debug
MSG
= getdiagnostics ();
# endif
console. writeline (MSG);
}

The above code runs well in the debug version, but a blank line is output in the release version. There is nothing to output a blank line, but it is not our original intention after all. The compiler cannot help us with our own bad things, because we have mixed the code that belongs to the main logic of the program with the Conditional compilation code. Using # If and # endif randomly in the source code makes it difficult for us to diagnose behavioral differences between different versions.
C # provides a better choice: the conditional feature. Using the conditional feature, we can isolate some functions so that they can only take effect after defining certain environment variables or setting a certain value. The most common feature of conditional is to adapt the Code to a debugging statement .. . NET Framework has provided support for related functions. The following code demonstrates the original work of the conditional feature and its applicability.

Private   Void Checkstate ()
{
// Obtain the name of the function being called:
String Methodname =  
New Stacktrace (). getframe ( 1 ). Getmethod (). Name;
Trace. writeline (
" Entering checkstate for person: " );
Trace. Write (
" \ Tcalled " );
Trace. writeline (methodname );
Debug. Assert (_ lastname
! =   Null , Methodname, " Last name cannot be null " );
Debug. Assert (_ lastname. Length
>   0 , Methodname, " Last name cannot be blank " );
Debug. Assert (_ firstname
! =   Null , Methodname, " First name cannot be null " );
Debug. Assert (_ firstname. Length
>   0 , Methodname, " First name cannot be blank " );
Trace. writeline (
" Exiting checkstate for person " );
}

We can also use it as a precondition and a postcondition to call it in all public and protected methods.

Public   String Lastname
{
Get
{
Checkstate ();
Return_ Lastname;
}

Set
{
Checkstate ();
_ Lastname
=Value;
Checkstate ();
}

}

When the first attempt is to set the lastname attribute to a null string or null, checkstate will cause an asserted error. In this way, the set accessors are corrected to check the parameters passed to the lastname. This is what we want.
However, this extra check in every public function is obviously a waste of time. We may just want it to appear in the debugging version. This requires the conditional feature:

[Conditional ( " Debug " )]
Private   Void Checkstate ()
{
//Code remains unchanged
}

After the conditional feature is applied, the C # compiler calls the checkstate method only when the debug environment variable is detected. The conditional feature does not affect the compilation of the checkstate () method. It only affects the call of this method. If a debug symbol is defined, the preceding lastname attribute is changed to the following code:
Public   String Lastname
{
Get
{
Checkstate ();
Return_ Lastname;
}

Set
{
Checkstate ();
_ Lastname
=Value;
Checkstate ();
}

}

Otherwise, the following code is obtained:

Public   String Lastname
{
Get
{
Return_ Lastname;
}

Set
{
_ Lastname
=Value;
}

}

Whether or not the debug symbol is defined, the checkstate () method remains unchanged. It will be compiled by C # and generated to the result set. This example shows the differences between the C # compiler compilation process and the JIT compilation process. This method seems to cause a little efficiency loss, but the cost is only the disk space. If the checkstate () method is not called, it is not loaded into the memory and compiled by JIT. The impact of generating the checkstate () method into the assembly is negligible. This strategy consumes a small amount of performance, but it is flexible.
The method we created can also depend on multiple environment variables. When we need multiple conditional features, the composite relationships between them will be "or.
The conditional feature can only be applied to the entire method. Note that any method using the conditional feature can only return the void type.
We cannot apply the conditional feature on a code block in a method, or on a method with a returned value. To apply the conditional feature, we need to separate conditional behaviors into a method. Although we still pay attention to the negative effects of the conditional methods on the object state, the isolation policies of the conditional feature are much better than that of the # If/# endif method.
To sum up, using the conditional feature is more efficient than using the Il code generated by # If/# endif. At the same time, we can clearly separate conditional code at the function level, so that our code has a better structure.

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.