Six ways to quickly fix C # bugs

Source: Internet
Author: User
Tags assert bool config functions log new features switches versions
NET Framework contains many tools that can be used to write the correct program faster and easier. But we have to face this situation: the emergence of bugs. No matter how simple the program is, programmers can make mistakes. In my experience, the bugs of most programs appears in the interface between programmers: When a programmer writes code that is called by another programmer. Somehow, the caller broke the assumptions that were made when the code was written. And whose fault is it? It doesn't matter, but more importantly, how quickly can you fix it? The following tips will help you find and solve these problems faster before the program is put into use. In the end, these tips will help you diagnose any problems that actually occur in use.

Test hypothetical conditions
Test assumptions are one of the most important ways to build the right program. When you write a function, you should consider and determine what assumptions you have made about that function. You should ask yourself the following questions:

1. When this function is called, what does this object have to be (initialization of an object, value of an intrinsic variable)?
2. When this function exists, what will this object be (still a #, but include the side effects of the function)?
3. What must be any parameter of the function (allow null values, what is the range of input values)?
4. What does the return value have to be?


Once you have asked yourself these four questions and answered them, put them in the code. In C #, it is represented by the assent method of the System.Diagnostics.Debug class: public bool Processiterations (int numiters) {Debug.Assert (Numiters > 0, "processiterations.", "iterations must is more than 0"); More code ...



The code fragment executes an assumption that the numiters parameter must be greater than 0. If you invoke processiterations with an invalid parameter, the assert is triggered. At this point, the program stops running and notifies the user of the error. declarations (assertions) are compiled only to programs in the debug version, so they do not affect performance in production.

Why use this method? Use this technique to ensure that the method of your class is quickly found to be used unexpectedly. Then, either the caller modifies his code or asks to modify it in the behavior of your class (behavior).




Validating 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 invoked, you should make sure that the implied assumptions are tested. The conditional compilation features of C # make this easy to implement.

First, write a private function to test the integrity of the object. When you do this, mark the method as "Conditional": [Conditional ("DEBUG")]private void Imok () {Debug.Assert (this!= null, "Testing the Object state "," This cannot to be null ");



Then, in each publicly-owned method, call the Imok method: public bool Processiterations (int numiters) {Imok ();D ebug. Assert (numiters > 0, "Processiterations.", "iterations must is more than 0");



In release versions, the compiler automatically cancels calls to Imok.

Why use this method? Using this technique, you can quickly discover any situation where your object's state becomes invalid.

Using Debug and trace output
Printing a diagnostic message can help you determine how your program is going wrong. You need to know what happens when an assert is triggered, and you usually 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 functions are called before a bug is present.

When you generate debug output, the. NET framework has some new features to use. The System.Diagnostic.Debug class allows you to format debug output and easily create different classes or levels of debug output. Here are some guidelines I like to use.

First, build a TraceSwitch object for each class in your program: public class Myclass{private static TraceSwitch Myclassswitch = new TraceSwitch (" Myclassswitch "," Controls the debug output of MyClass ");



Then, use the WriteIf () and WriteLineIf () methods to record any information that you feel will help you track your program: public bool Processiterations (int numiters) {WriteLineIf ( Myclassswitch.traceinfo, "Entering Processiterations", "Calltrace"); Imok ();D ebug. Assert (numiters > 0, "Processiterations.", "iterations must is more than 0");



I prefer to use WriteLineIf (), which prints out the error message and the type of error. The first parameter contains a value for the debug switch, allowing you to control what level of output to print.




The use of System.Diagnostics.Trace is exactly the same as the use of Debug. The difference is that debug is only compiled into the debug version, and the trace statement is compiled into the debug and release versions. Therefore, the use of trace statements should be more cautious. Use trace statements in code that can help you discover bugs or capture usage features in programming combat.

Why use this method? Use these methods to let you know the sequence of code execution. This helps you to determine what action (actions) you have before the program goes wrong.

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. Build an XML file in the application directory that has the same name as your program, with the extension ". config". For example, if your program is MyApp.exe, build a 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>



The file sets the value of Myclassswitch to 4, which conforms to the "Info" setting. By editing this config file, you can change the level of any switch in your program.

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

Set up your listeners.
The. NET framework has a listeners collection that represents objects that receive debug, assert, and trace output. By default, your application has a single defaulttracelistener. This listener ignores the debug and trace output and displays a dialog box for an assert message. You can add items to this collection, or delete items from this collection. The two items that have been created for you are TextWriterTraceListener and EventLogTraceListener. TextWriterTraceListener writes the message to a stream, EventLogTraceListener writes the message to a eventlog. EventLog allows you to write debug and trace messages for your program into system event log records.

I like to build a debug log file for all programs: static void Main () {DEBUG.LISTENERS.ADD (New textwritetracelistener ("MyLog.log");



Why use this method? This technique allows you to control where to use Debug and trace statements.

When you find bugs, use these tips
Frankly, no one uses all of these techniques when it comes to writing code. In fact, we usually add these statements when we are trying to find out the reasons for those significant bugs. When you get into that dilemma, try the following:

1. When you create a class, you typically build a tracking switch for each class.
2. Typically, a validation function is built for each class.
3. When you want to diagnose the wrong behavior, add other trace and debug statements. Be sure to keep these changes in your code. One of the most common mistakes I've found is that when programmers want to find bugs, they add a lot of trace and debug statements to find errors. Then, once they find the error they are looking for, they delete the statements.


These tools will help you find and repair bugs, and it's up to you to use them.




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.