C #8 Reasons for too many comments in the program

Source: Internet
Author: User
Tags mailmessage smtpclient
ArticleDirectory
    • 1. When a method call is moved to a new type, the original method is retained in the original type.
    • 2. Delete unnecessary conditions or situations because the code is not deleted due to insufficient consideration.
    • 3. due to incomplete consideration, comments and functions in the Code coexist. Annotations are retained to help analyze code when an error occurs.
    • 4. The exception handling mechanism is changed, causing the code caught in the code to be commented out.
    • 5. The development of the. NET Framework leads to unnecessary code that has not been deleted. comment out the code first.
    • 6. Change the runtime environment and comment out the code to facilitate future troubleshooting.
    • 7. the test data is retained in the code in the form of comments, and the interpretation of the Code is added.
    • 8. comments are made for each data item. Necessary comments and unnecessary comments are mixed together.

ProgramAnnotations in, in general, are helpful. You can know some logic descriptions of the program or parameter interpretations. However, some programs are inconvenient to maintain because of too many comments. If you delete the program, you may not be able to find the cause of the problem. If you do not delete the program, you will not be able to delete it.CodeProgram maintenance personnel, is a kind of pain.

The following lists the causes that I can understand for your reference.

1. When a method call is moved to a new type, the original method is retained in the original type.
// Public void executesqlcommand (string sqlcommandtext)//{// This. executesqlcommand (sqlcommandtext, commandtype. Text, null );//}......
 
 

The executesqlcommand method has been transplanted to the new helper type sqlhelper, but this method has not been directly deleted. There may be reflection calls for the purpose of reservation. After an error is reported, the code is commented out and the new ownership of the code will be searched again.

 

2. Delete unnecessary conditions or situations because the code is not deleted due to insufficient consideration.
  Static Clientproxyfactory () {_ managertypeassemblies = New List < String > (); _ Managertypescache = New Dictionary < String , Type> (); _ managerinstancescache = New Dictionary < String , Imanagerbase> (); enablemanagerinstancecache = True ; // If (platform = communicationplatform. Local)              //{              // Foreach (string file in managerassembly)              //{              // If (file. exists (string. Format ("{0}. dll", file )))              //{              // Assembly = assembly. Load (File );              // _ Managertypeassemblies. Add (assembly );              //}             //}              //} }......

In the above Code, when communicationplatform is local, It is commented out but not deleted directly. The commented code is used to add the assembly to the _ managertypeassemblies type. The possible cause is that the system does not support the local mode, but only the. NET remoting mode, so this code will be commented out.

 

3. due to incomplete consideration, comments and functions in the Code coexist. Annotations are retained to help analyze code when an error occurs.

Let's take a look at the definitions of the two common methods below. One is to call static methods through reflection, and the other is to call the value of static properties through reflection.

  /// <Summary>  /// Call a static method  /// </Summary>  /// <Param name = "file"> </param>  /// <Param name = "typename"> </param>  /// <Param name = "methodname"> </param>  /// <Returns> </returns>  Public   Static   Object Invokestaticmethod (type typename, String Methodname, Object [] ARGs ){// Assembly = assembly. LoadFile (File );              // Type = assembly. GetType (typename ); Assembly = typename. assembly; // Obj2 = activator. createinstance (type, argS ); System. reflection. methodinfo method = typename. getmethod (methodname, New Type [] { Typeof ( Object )}); // Object OBJ = assembly. createinstance (typename );             // Object OBJ = activator. createinstance (typename, argS );              Return Typename. invokemember (methodname, bindingflags. Public | bindingflags. Static, Null , Null , ArgS );} Public   Static   Object Getstaticpropertyvalue (type, String Propertyname ){ Object Objec = createobjectinstance (type); propertyinfo = type. getproperty (propertyname, bindingflags. Public | bindingflags. Static | bindingflags. declaredonly ); // Type. getproperty (propertyname). getvalue (null, null );              Return Propertyinfo. getvalue (objec, Null );}

 

From the commented code above, we can see that the required code and the commented code coexist. The annotated code can be run correctly because of different parameters or conditions. However, the code that is not commented can be run only in the current situation. There are many considerations for the Development of Public frameworks, and tests must be sufficient to ensure that there is no error. It can also be seen from this that reflection brings obstacles to code refactoring, because it does not know where the code is called by reflection, so the code can only be found after an error occurs.

Unless it cannot be implemented under normal calls, the reflection call code should be reduced. Or encapsulate the reflection call code. All reflection calls are placed in a reflectionhelper type. To locate the problem, you only need to break the breakpoint in the corresponding method of this type.

 

4. The exception handling mechanism is changed, causing the code caught in the code to be commented out.

See the following two methods for copying files and directories.

 // Bakup File  Public   Static Backupfile ( String Sourcefilename, String Destfilename ){ Try {System. Io. file. Copy (sourcefilename, destfilename, True ); Return   True ;} Catch (Exception e ){ Throw E ;}} Public  Static   Void Copydirectory ( String Olddir, String Newdir ){ Try {Directoryinfo dinfo = New Directoryinfo (olddir); copydirinfo (dinfo, olddir, newdir );} Catch (Exception exc ){ Throw   New Exception (EXC. tostring ());}}

If true or false is returned, the code execution is successful. I hate such code now. If an error occurs when copying a file or copying a directory, no error is reported. The exception is caught here. In the second method, when an exception is thrown in copydirectory, the stack information of the exception is changed, which makes it difficult to detect the error. If it is a winforms program, handle exceptions in the following ways:

Customexceptionhandler Eh =NewCustomexceptionhandler (); appdomain. currentdomain. unhandledexception + =NewUnhandledexceptioneventhandler (customexceptionhandler. currentdomain_unhandledexception); application. threadexception + =NewThreadexceptioneventhandler (Eh. onthreadexception );

At the entrance of the program, set the unhandledexception and threadexception handling conditions. If an exception occurs in the program, the process will jump to here for unified processing. In my practice, methods like the following should not be handled in this way.

/// <Summary>/// Copy the file. If the target file already exists, it will be overwritten./// </Summary>/// <Param name = "oldfile"> source file </param>/// <Param name = "newfile"> target file </param>Public Static VoidCopyfile (StringOldfile,StringNewfile ){Try{File. Copy (oldfile, newfile,True);}Catch(Exception exc ){Throw NewException (EXC. tostring ());}}

After modifying the exception capture policy, the Code is as unfriendly as it is.

  //    // copy a file, if the target file already exists, overwrite   ///   / //  source file    //  target file    Public   static   "> void  copyfile ( string  oldfile,  string  newfile) { // try   // { file. copy (oldfile, newfile,  true  ); ///}   // catch (exception exc)   // {  // throw new exception (EXC. tostring ();  //}}

You should directly remove this method encapsulation and directly call file. copy in the code.

 

5. The development of the. NET Framework leads to unnecessary code that has not been deleted. comment out the code first.

When the field columns of the SELECT statement are dynamically constructed, a comma is usually added to them after the construction is complete.

 
SelectItem_no, item_groupFromGbitem
 

 

Generally, we use arraylist or ilist <string> to aggregate item_no and item_group, and recycle them once. Add a comma at the end of each character, and finally remove unnecessary commas:

  Public   static   string  arraytolist ( string  [] IDs,  string  separativesign) { int  num = 0;  string  STR =  string . empty;  foreach  ( string  str2  in  IDs) {num ++;  string  str3 = STR; STR = str3 + separativesign + str2 + separativesign +  ","  ;}  If  (num = 0) { return   ""  ;}  return  Str. trimend ( New   char  [] {', '}) ;}

In msdn, the join method of string type can achieve this goal. You only need to call the join method. The following are examples in msdn:

If separator is "," and the value element is "apple", "orange", "grape", and "Pear", then join (separator, value) returns "Apple, orange, grape, pear ". If separator is a nullnothingnullptrnull reference (nothing in Visual Basic), use an empty string (empty ).

 
 
 
 
6. Change the runtime environment and comment out the code to facilitate future troubleshooting.

Please refer to the following method example

  /// <Summary>          /// Obtain the absolute path of a file (applicable to Web applications)          /// </Summary>          /// <Param name = "filepath"> file path </param>          /// <Returns> string </returns>          Public   Static   String Getrealfile (String Filepath ){ String Strresult = "" ; // Strresult = (file. indexof (@ ": \")> 0 | file. indexof (":/")> 0 )? File: system. Web. httpcontext. Current. server. mappath (system. Web. httpcontext. Current. Request. applicationpath + "/" + file )); Strresult = (filepath. indexof (": \")> 0 )? Filepath: system. Web. httpcontext. Current. server. mappath (filepath )); Return Strresult ;}

This method may have been previously used in the Web environment. Now it is changed to winforms or a console project. As a result, the annotated code reports an error and comments it. For path selection, the basedirectory or application. executepath of appdomain is independent of the runtime environment (ASP. NET, console, winforms, and Windows Services), and should be used preferentially.

 

7. the test data is retained in the code in the form of comments, and the interpretation of the Code is added.
 StringHost = system. configuration. configurationmanager. receivettings ["Emailhost"]; Mailmessage M =NewMailmessage (); M. Subject = subject; M. subjectencoding = encoding. utf8; M. From =NewMailaddress (from); M. to. Add (to); M. Body = body; M. bodyencoding = encoding. utf8; M. isbodyhtml =True; Smtpclient client =NewSmtpclient (); client. Host = host;// "Ashkgex4.asia.ad.flextronics.com ";Client. Credentials =NewSystem. net. networkcredential ("Asia \ baoshhli",""); Client. Port = 25; client. deliverymethod = smtpdeliverymethod. Network; client. usedefacrecredentials =False; Client. Send (m );
 
 

For example, if the host = ashkgex4.asia.ad.flextronics.com in the above code is used to test the problem, no error is reported for this host. Therefore, the data is kept in the Code to facilitate the code maintenance personnel to test the problem later.

 

8. comments are made for each data item. Necessary comments and unnecessary comments are mixed together.

For example, the following code

 
Datatable dt =NewDatatable (); datarow Dr; DT. Columns. Add ("Name");// NameDT. Columns. Add ("Type");// Type: 1 is a folder, 2 is a fileDT. Columns. Add ("Size");// File size. If it is a folder, it is left empty.DT. Columns. Add ("Content_type");// File MIME type. If it is a folder, it is left empty.DT. Columns. Add ("Createtime");// Creation TimeDT. Columns. Add ("Lastwritetime"); // The last modification time.

Some of the fields after the add method are redundant. Some are necessary.

I thought the additional comments were:Name,Creation TimeThe value of the last modification time column can be known through the code or its own name.

I think it is necessary to comment the type column, which can reduce the workload of maintenance personnel.

 

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.