Write the correct program with assertions

Source: Internet
Author: User

. NET Framework contains many tools that can be used to write the right program faster and easier. But we have to face this situation: the emergence of bugs. No matter how simple the program is, programmers may make mistakes. In my experience, most program buckets appear on interfaces between programmers: When the code written by one programmer is called by another programmer. Somehow, the caller breaks the assumptions made during code writing. Who is at fault? It doesn't matter. What's more important is that you can fix it quickly? The following tips help you discover and solve these problems faster before the program is put into use. In the end, these skills will help you diagnose any problems that actually occur during use.

Test hypothesis
Test hypothesis conditions are the most important way to build a correct program. When writing a function, you should consider and determine what assumptions you have made for that function. You should ask yourself the following questions:

1. What must this object be like when this function is called (an internal variable value )?
2. What will happen to this object when this function exists (still #1, but including the side effects of this function )?
3. What must be the value of any parameter of the function (can null values be allowed, and what is the input value range )?
4. What is the returned value?

Once you have asked yourself these four questions and answered them, put them in the code. In C #, use the assent method of the system. Diagnostics. debug class to represent: Public bool processiterations (int
Numiters)
{
Debug. Assert (numiters> 0,
"Processiterations .",
"Iterations must be more than 0 ");
// More code...

 

This code snippet executes the assumption that the numiters parameter must be greater than zero. If you call processiterations with an invalid parameter, the assert is triggered. At this time, the program stops running and notifies the user of the error. Declarations are compiled only to programs in the debug version, so they do not affect the performance in production.

Why is this method used? Using this technique ensures that you can quickly discover unexpected usage of your class methods. Then, the caller can modify the code or request that the code be modified in the behavior of your class.

Verify integrity
Most functions in a C # program are instance methods on an object. There are implied assumptions about the valid state of any object. When a public method is called, make sure that the implied assumptions are tested. C #'s Conditional compilation feature makes this easy to implement.

First, write a private function to test the Object Integrity. When you do this, Mark this method as "Conditional": [conditional ("debug")]
Private void imok ()
{
Debug. Assert (this! = NULL,
"Testing object state ",
"This cannot be null ");
// More here.
}

 

Then, in each public method, call the imok method: Public bool processiterations (int
Numiters)
{
Imok ();
Debug. Assert (numiters> 0,
"Processiterations .",
"Iterations must be more than 0 ");

 

In the release version, the compiler automatically cancels the call to imok.

Why is this method used? With this technique, you can quickly find any situation where your object status becomes invalid.

Use debug and trace to output
Print the Diagnostic message to help you determine how your program went wrong. You need to know what happens when an Assert is triggered; you also need to know what happened before that. The best way to know this is to use your code so that you can easily see what function is called before a bug occurs.

When generating debugging output,. NET Framework has some new functions available. The system. Diagnostic. debug class allows you to format debugging output and easily create debugging output of different classes or levels. Below are some guidelines I like to use.

First, create a traceswitch object for each class in your program: public class myclass
{
Private Static traceswitch
Myclassswitch = new traceswitch
("Myclassswitch", "controls/
Debug output of myclass ");

 

Then, use the writeif () and writelineif () Methods to record any information that you think helps you track your program: Public bool processiterations (int
Numiters)
{
Writelineif
(Myclassswitch. traceinfo,
"Entering processiterations ",
"Calltrace ");
Imok ();
Debug. Assert (numiters> 0,
"Processiterations .",
"Iterations must be more than 0 ");

I prefer writelineif (), which can print error messages and types. The first parameter contains a value for debugging the switch, allowing you to control the output level of the print.

The use of system. Diagnostics. Trace is exactly the same as that of debug. The difference is that debug is only compiled into the debug version, while the trace statement is compiled into the debug and release versions. Therefore, use trace statements with greater caution. Using trace statements can help you discover the bugs or capture the code using features in programming practice.

Why is this method used? By using these methods, you can know the sequence of code execution. This helps you determine what actions (Actions) occur before a program error occurs ).

Dynamically control output
The biggest benefit of these new. NET Framework classes is that by editing a configuration file, you can change the level of any trace switch. Create an XML file in the application directory. The file name is the same as that of your program and the extension is ". config ". For example, if your program is myapp.exe, create myapp.exe. config. You can use this file to set the value of your tracking switch. For example, the following file: <? XML version = "1.0"?>
<Configuration>
<System. Diagnostics>
<Switches>
<Add name = "myclassswitch"
Value = "4"/>
</Switches>
</System. Diagnostics>
</Configuration>

 

This file sets the value of myclassswitch to 4, which complies with the "info" setting. By editing the config file only, you can change the level of any switch in your program.

Why is this method used? By using multiple switches and creating the appropriate config file, you can change the record output and focus on the elements you are concerned about.

Set your listeners
. NET Framework has a listeners set that represents the objects that receive debug, assert, and trace output. By default, your application has a single defaulttracelistener. This listener ignores debug and Trace Output and displays an Assert message dialog box. You can add a project to or delete a project from the collection. The two items you have created are textwritertracelistener and eventlogtracelistener. Textwritertracelistener writes a message to a stream, and eventlogtracelistener writes the message to an EventLog. EventLog allows you to write debugging and tracing messages of your program to system event log records.

I like to create a debug log file for all programs: static void main ()
{
Debug. listeners. Add (
New textwritetracelistener
("Mylog. log ");
// Etc.

 

Why is this method used? This technique allows you to control where debugging and tracing statements are used.

Use these skills when you discover a bugs
Frankly speaking, no one started writing code with all these skills. In fact, when we try to find out the cause of the major bugs, we usually add these statements. When you are in that dilemma, try the following methods:

1. When you create a class, you usually create a trail switch for each class.
2. A verification function is usually created for each class.
3. When you want to diagnose incorrect behaviors, add other tracing and debugging statements. Be sure to keep these changes in the Code. One of the most common errors I have found is that when programmers want to find the bugs, they add many trace and debug statements to find errors. Then, once they find the error they are looking for, they will delete these statements.

These tools will help you find and repair the bugs, and you don't need them anymore.

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.